Reputation: 41
var one = "mb50 mt60";
How can I put the next two characters after a specific character into its own string?
For example: From the code above, I want the number 50 in its own string. I need it to look for the 'mb', then take the next two characters.
I can't use indexOf because the characters may be in a different place each time.
Upvotes: 0
Views: 302
Reputation: 3919
With a regex like that:
str.match(/mb(.{2})/)[1]
If there is more than one "next two characters" to capture, you should use replace:
var one= "mb50 mt60 mb20";
var results = [];
one.replace(/mb(.{2})/g, function() {
results.push(arguments[1]);
});
console.log(results);
Upvotes: 1
Reputation: 1720
You can try doing it something like this
var string = "mb50 foo300",
search = 'foo';
console.log(string.substr(string.indexOf(search) + search.length, 2));
or the regex way as Gael suggested.
Upvotes: 2
Reputation: 327
You can use regular expressions, like:
var one = "mb50 mt60";
var regex = /mb(\d+)/g;
console.log(regex.exec(one)[1]); // => '50'
Upvotes: 2