在JavaScript中,如果你想存储一个字符串中所有特定字符出现的行号,你可以使用正则表达式来匹配这些字符,并通过遍历字符串来获取每一行的行号。下面是一个简单的函数,它可以实现这个功能:
function findCharLineNumbers(str, char) {
const lines = str.split('\n'); // 将字符串分割成行数组
const lineNumbers = []; // 存储行号的数组
lines.forEach((line, index) => {
if (line.includes(char)) { // 检查当前行是否包含特定字符
lineNumbers.push(index + 1); // 如果包含,则将行号(从1开始)添加到数组中
}
});
return lineNumbers;
}
// 示例使用
const text = `Hello world
This is a test.
Char is here.
Another line.`;
const charToFind = 'is';
const result = findCharLineNumbers(text, charToFind);
console.log(`The character '${charToFind}' is found on lines: ${result.join(', ')}`);
split('\n')
方法用于将字符串按行分割成一个数组。forEach
方法用于遍历数组中的每一项。includes(char)
方法用于检查字符串中是否包含特定的字符。\r\n
,Unix使用\n
)。可以使用正则表达式来兼容不同的换行符:\r\n
,Unix使用\n
)。可以使用正则表达式来兼容不同的换行符:通过这种方式,你可以有效地找到并记录特定字符在文本中的所有出现行号。
领取专属 10元无门槛券
手把手带您无忧上云