查找字符串中字符的第二次出现



我听说JavaScript有一个名为search()的函数,它可以在另一个字符串(B(中搜索一个字符串(让我们称之为A(,它将返回在B中找到A的第一个位置。

var str = "Ana has apples!";
var n = str.search(" ");

代码应返回 3,因为它是在str中找到空间的第一个位置。

我想知道是否有一个函数可以在我的字符串中找到下一个空格。

例如,我想找到字符串中第一个单词的长度,如果我知道它的起始位置和结束位置,我可以轻松做到这一点。

如果有这样的功能,对于这样的事情,还有比它更好的吗?

你需要使用String.indexOf方法。它接受以下参数:

str.indexOf(searchValue[, fromIndex])

所以你可以这样做:

var str = "Ana has apples!";
var pos1 = str.indexOf(" ");           // 3
var pos2 = str.indexOf(" ", pos1 + 1); // 7
console.log(pos2 - pos1 - 1);          // 3... length of the second word

.indexOf(…)将为您提供" "的第一次出现(从 0 开始(:

var str = "Ana has apples!";
var n = str.indexOf(" ");
console.log(n);

如果您想要所有事件,可以使用带有whileRegExp轻松实现:

var str = "Ana has apples! A lot.";
var re = new RegExp(" ","ig");
var spaces = [];
while ((match = re.exec(str))) {
spaces.push(match.index);
}
// Output the whole array of results
console.log(spaces);
// You can also access the spaces position separately:
console.log('1st space:', spaces[0]);
console.log('2nd space:', spaces[1]);


⋅ ⋅ ⋅

或。。。您可以使用do {} while ()循环:

var str = "Ana has apples! A lot.";
var i = 0,
n = 0;
do {
n = str.indexOf(" ");
if (n > -1) {
i += n;
console.log(i);
str = str.slice(n + 1);
i++;
}
}
while (n > -1);

然后,您可以对它进行函数:

var str = "Ana has apples! A lot.";
// Function
function indexsOf(str, sub) {
var arr = [],
i = 0,
n = 0;
do {
n = str.indexOf(" ");
if (n > -1) {
i += n;
arr.push(i);
str = str.slice(n + 1);
i++;
}
}
while (n > -1);
return arr;
}
var spaces = indexsOf(str, ' ')
// Output the whole array of results
console.log(spaces);
// You can also access the spaces position separately:
console.log('1st space:', spaces[0]);
console.log('2nd space:', spaces[1]);


⋅ ⋅ ⋅

希望对您有所帮助。

更好的匹配是使用regex。有选项,例如使用组'g'标志的匹配

var str = "Ana has apples  !";
var regBuilder = new RegExp(" ","ig");
var matched = "";
while((matched = regBuilder.exec(str))){
console.log(matched + ", position : " +matched.index);
}
str = "Ana is Ana no one is better than Ana";
regBuilder = new RegExp("Ana","ig");
while((matched = regBuilder.exec(str))){
console.log(matched + ", position : " +matched.index);
}


'i'用于忽略区分大小写的标志 您也可以在此处检查其他标志

试试这个:

const str = "Ana has apples!";
const spaces = str.split('')
.map((c, i) => (c === ' ') ? i : -1)
.filter((c) => c !== -1);
console.log(spaces);

然后您将所有空间位置。

最新更新