Patrick Beardmore
Patrick Beardmore

Reputation: 1032

Quick Problem - Extracting numbers from a string

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.

Upvotes: 2

Views: 298

Answers (4)

karim79
karim79

Reputation: 342775

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]; 

Upvotes: 3

meder omuraliev
meder omuraliev

Reputation: 186762

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

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

Upvotes: 1

gnarf
gnarf

Reputation: 106412

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.

Upvotes: 1

Gavin Gilmour
Gavin Gilmour

Reputation: 6981

Use regular expressions:-

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

alert(match);

Upvotes: 1

Related Questions