在字符串中查找字符的第二个出现位置

4

我听说 JavaScript 有一个名为 search() 的函数,可以在一个字符串 B 中搜索另一个字符串 A,并返回 A 在 B 中第一次出现的位置。

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

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

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

例如,如果我知道单词的起始位置和结束位置,我就可以轻松地找出我的字符串中第一个单词的长度。

如果有这样的函数,请问有没有更好的函数来处理这些事情?


2
你要找的是 indexOf(),而不是 search() - connexo
1
你一定想使用 str.indexOf(…)(其中 str 是你的字符串)。 - Takit Isy
2
String.indexOf() 是什么?https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf - Seblor
.indexOf()会给你索引。.includes()会给你真或假。你可以在MDN或其他规范网站上很容易地查找这些内容,无需发布关于基本语法的问题。 - Shilly
不,没有预先制作的函数可以告诉您可以找到某个子字符串的所有位置。 - connexo
使用 str.indexOf(' ', n),其中 n 是开始搜索的索引。更多信息请参见:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf。 - VisioN
4个回答

14

您需要使用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


2

.indexOf(…) 方法可以给你第一次出现的" "(从0开始):

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

如果您想获取所有匹配项,可以使用带有“while”的RegExp轻松实现:

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]);


⋅ ⋅ ⋅

希望这能有所帮助。


虽然您的算法有效,但结果中所有索引号都要+1。 - connexo
嗯,@connexo,我已经更正了。但是一开始这是想要的行为。因为代码更简单。(而且我不喜欢.indexOf从0开始) :) - Takit Isy

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' 标志用于 忽略大小写 您还可以在这里查看其他标志。


1

试试这个:

const str = "Ana has apples!";

const spaces = str.split('')
                  .map((c, i) => (c === ' ') ? i : -1)
                  .filter((c) => c !== -1);

console.log(spaces);

然后你将得到所有空格的位置。

空格位置怎么样?这就是原帖提出的问题。 - Takit Isy
你是正确的,我误解了OP的问题并编辑了我的帖子。 - Alex G

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接