4

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?

Salman A
  • 262,204
  • 82
  • 430
  • 521
Ionut Eugen
  • 481
  • 2
  • 6
  • 27
  • 2
    You are looking for `indexOf()`, not `search()`. – connexo Jun 29 '18 at 12:08
  • 1
    You must want to use `str.indexOf(…)` (where `str` is your string). – Takit Isy Jun 29 '18 at 12:08
  • 2
    `String.indexOf()` ? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf – Seblor Jun 29 '18 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 Jun 29 '18 at 12:09
  • No, there is no pre-made function that will tell you all positions where a certain substring can be found. – connexo Jun 29 '18 at 12:10
  • Use `str.indexOf(' ', n)`, where `n` is the index at which to start the search. More here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf. – VisioN Jun 29 '18 at 12:10

4 Answers4

13

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
Salman A
  • 262,204
  • 82
  • 430
  • 521
2

.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.

Takit Isy
  • 9,688
  • 3
  • 23
  • 47
  • While your algorithm works, all the index numbers are +1 in your result. – connexo Jun 29 '18 at 12:36
  • Well, @connexo I corrected that. But it was a wanted behaviour at first. Because the code was easier. (And I don't like that `.indexOf` starts at 0) :) – Takit Isy Jun 29 '18 at 12:44
1

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

Onk_r
  • 836
  • 4
  • 21
1

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.

Alex G
  • 1,897
  • 2
  • 10
  • 15