Ad

JavaScript Substring Missing Characters?

- 1 answer

I am trying to use substring to differentiate between data in JavaScript. The raw data I am pulling is:

The code I am using is

var contents = '0.! 3.0011632! \
0.01! 2.9417362! ';

var lastPosition = 0;
var count = 0;
//This code will continue looking for ! until it reaches three occurances
while (count < 3) {
  //contents is a string variable that contains all data.
  console.log(lastPosition);
  console.log(contents.indexOf("!", lastPosition + 1));
  console.log(contents.substr(lastPosition + 1, contents.indexOf("!", lastPosition + 1)));
  lastPosition = contents.indexOf("!", lastPosition + 1);
  count++;
}

The problem is the output I am getting is:

0 //start
3 //end
0.! //#
3 //start
14 //end
3.0011632! //#
14 //start
23 //end 
0.01! 2.9417362! //# 

As you can see its not properly locating the ! at the third cycle. This continues with more data and it eventually starts missing more and more !'s. Can anyone tell me what I'm doing wrong here?

Ad

Answer

Use a regular expression to match a string that ends with !. The g modifier makes it match all the occurrences and return an array of the matches. Then I use .slice() to get just the first 3.

var contents = '0.! 3.0011632! \
0.01! 2.9417362! ';
var matches = contents.match(/[^!]*!/g).slice(0, 3);
console.log(matches);

Ad
source: stackoverflow.com
Ad