Quick problem. Extracting numbers from a string.
I need to extract one variable number from a string. The line always looks like this:
javascript:change(5);
with a variable that is 5.
How can I isolate it? Thank you very much in advance.
+2
Patrick beardmore
source
to share
4 answers
Here's one way, assuming the number is always surrounded by parentheses:
var str = 'javascript:change(5);';
var lastBit = str.split('(')[1];
var num = lastBit.split(')')[0];
+3
karim79
source
to share
Use regular expressions : -
var test = "javascript:change(5);"
var number = new RegExp("\\d+", "g")
var match = test.match(number);
alert(match);
+1
Gavin gilmour
source
to share
A simple RegExp can solve this problem:
var inputString = 'javascript:change(5);';
var results = /javascript:change\((\d+)\)/.exec(inputString);
if (results)
{
alert(results[1]); // 5
}
Using a part javascript:change
in a match also ensures that if the string is not in the correct format, you don't get a value from the matches.
+1
gnarf
source
to share
var str = 'javascript:change(5);', result = str.match(/\((\d+)\)/);
if ( result ) {
alert( result[1] )
}
+1
meder omuraliev
source
to share