最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Find second occurrence of a character in a string - Stack Overflow

programmeradmin2浏览0评论

I have heard that JavaScript has a function called search() that can search for a string ( lets call it A ) in another string ( B ) and it will return the first position at which A was found in B.

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

The code should return 3 as its the first position in which the space was found in str.

And I was wondering if there is a function that can find the next spaces in my string.

For example I want to find the length of the first word in my string and I could easily do this If I knew the its starting position and its ending one.

If there is such a function, are there any better than it for such things?

I have heard that JavaScript has a function called search() that can search for a string ( lets call it A ) in another string ( B ) and it will return the first position at which A was found in B.

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

The code should return 3 as its the first position in which the space was found in str.

And I was wondering if there is a function that can find the next spaces in my string.

For example I want to find the length of the first word in my string and I could easily do this If I knew the its starting position and its ending one.

If there is such a function, are there any better than it for such things?

Share Improve this question edited Jun 29, 2018 at 16:27 Salman Arshad 272k84 gold badges442 silver badges533 bronze badges asked Jun 29, 2018 at 12:06 Ionut EugenIonut Eugen 5012 gold badges6 silver badges27 bronze badges 6
  • 2 You are looking for indexOf(), not search(). – connexo Commented Jun 29, 2018 at 12:08
  • 1 You must want to use str.indexOf(…) (where str is your string). – Takit Isy Commented Jun 29, 2018 at 12:08
  • 2 String.indexOf() ? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Seblor Commented Jun 29, 2018 at 12:08
  • .indexOf() gives you the index. .includes() will give you true or false. You can look up thse kind of things very easily on MDN or a different specification site, no need to post questions about basic syntax. – Shilly Commented Jun 29, 2018 at 12:09
  • No, there is no pre-made function that will tell you all positions where a certain substring can be found. – connexo Commented Jun 29, 2018 at 12:10
 |  Show 1 more comment

4 Answers 4

Reset to default 14

You need to use String.indexOf method. It accepts the following arguments:

str.indexOf(searchValue[, fromIndex])

So you can do this:

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(…) will give you the first occurence of the " " (starting at 0):

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

If you want all occurences, this can be achieved easily using a RegExp with a 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]);


⋅ ⋅ ⋅

Or… you can use a do {} while () loop:

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

Then, you can make a function of it:

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


⋅ ⋅ ⋅

Hope it helps.

Better for matching is to use regex. There is option like match group using group 'g' flag

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' flag used to ignore case sensitive You can check for other flags too here

Try this:

const str = "Ana has apples!";

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

console.log(spaces);

Then you will all the spaces positions.

发布评论

评论列表(0)

  1. 暂无评论