我听说JavaScript具有一个名为search()
的函数,该函数可以在另一个字符串(B)中搜索一个字符串(叫作A),并且它将返回在B中找到A的第一个位置。
var str = "Ana has apples!";
var n = str.search(" ");
代码应返回3作为在str
中发现空格的第一个位置。
我想知道是否有一个函数可以在字符串中找到下一个空格。
例如,我想找到字符串中第一个单词的长度,如果我知道它的开始位置和结束位置,就可以轻松地做到这一点。
如果有这样的功能,那么有什么比这更好的了吗?
答案 0 :(得分:2)
您需要使用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... the result you were expecting
答案 1 :(得分:0)
.indexOf(…)
将为您提供" "
的首次出现(从0开始):
var str = "Ana has apples!";
var n = str.indexOf(" ");
console.log(n);
如果您希望所有事件都发生,可以使用带有RegExp
的{{1}}来轻松实现:
while
⋅ ⋅ ⋅
或者…您可以使用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);
⋅ ⋅ ⋅
希望有帮助。
答案 2 :(得分:0)
更好的匹配方法是使用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'
标志用于忽略大小写
您也可以检查其他标志here
答案 3 :(得分:0)
尝试一下:
const str = "Ana has apples!";
const spaces = str.split('')
.map((c, i) => (c === ' ') ? i : -1)
.filter((c) => c !== -1);
console.log(spaces);
然后您将在所有空格位置放置
。