views:

129

answers:

4

I need to extract a single variable number from a string. The string always looks like this:

javascript:change(5);

with the variable being 5.
How can I isolate it? Many thanks in advance.

+2  A: 

Here is 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];
karim79
Thanks. That makes great sense.Very grateful for the other solutions too.
Patrick Beardmore
A down-vote because someone is just too big a fan of regexes to let this go?
karim79
Or because it's unnecessarily complicated, with unneeded temporaries, and the problem spec is quite simply "find the number among this stuff that's not number"? `/(\d+)/` is the simplest way to do that, and `/javascript:change\((\d+)\);/` additionally verifies that the surrounding data is in the expected form. `split` is excessively clever.
hobbs
@hobbs - disagree, because the OP is clearly interested in grabbing an actual parameter from a function call (be it a number or whatever) and this will work irrespective of the (contents). The regex solution breaks for anything else.
karim79
@karim79 - not irrespective on the contents. It breaks for `javascript:change('(5)');`. In fact yours will only return `'` - the regexp will just fail... I'd rather get no parameter found than a `'` back from this sort of function.
gnarf
+1  A: 

Use regular expressions:-

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

alert(match);
Gavin Gilmour
+1  A: 

A simple RegExp can solve this one:

var inputString = 'javascript:change(5);';
var results = /javascript:change\((\d+)\)/.exec(inputString);
if (results)
{
  alert(results[1]);  // 5
}

Using the javascript:change part in the match as well ensures that if the string isn't in the proper format, you wont get a value from the matches.

gnarf
Why the downvote?
gnarf
+1  A: 
var str = 'javascript:change(5);', result = str.match(/\((\d+)\)/);

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