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


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


source


Use regular expressions : -



var test = "javascript:change(5);"
var number = new RegExp("\\d+", "g")
var match = test.match(number);

alert(match);

      

+1


source


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


source


var str = 'javascript:change(5);', result = str.match(/\((\d+)\)/);

if ( result ) {
    alert( result[1] ) 
}

      

+1


source







All Articles