views:

126

answers:

6

How to split these strings in jquery?

  • Mode1
  • 2Level

I want to get only the numbers from the above two strings in jquery... The strings may be Mode11,Mode111,22Level,222Level etc the characters Mode and Level wont change...

+1  A: 

Try this:

var num = parseInt(myString.match(/\d+/)[0]);
Jasie
What's `string`? And why are you passing `myString` as the second argument to a non-existent `match` method? I think what you meant was `myString.match(/\d+/)`...
J-P
Also, the match operation will return an array of matches, not a single number.
J-P
Yes, you are right, the syntax was wrong.
Jasie
A: 

You could do something like this:

var numbers = "Mode111".match(/\d/g).join("")
var alpha = "Mode111".match(/[a-z]/gi).join("")

I think there is an easier way with match collections but I can't find anything to show whether javascript supports them. I will see if I can find it.

spinon
The only assumption that this code is making is that string will always be defined and not an undefined object. But I didn't think that would be a problem.
spinon
A: 

You probably want the String.prototype.match method:

var str = 'Mode1';
var match = str.match(/\d+/);
var number = match && +match[0];
// If `str` contained no numbers then number === null

The unary plus operator (+) casts its operand to an actual number (from a string containing numbers).

J-P
A: 
var str = 'Mode123';
var num = str.match(/\d/g).join('');

or

var num = str.replace(/\D/g,'');
David
The second example would be better with `/\D+/g` as this will match *all* non-digit characters.
J-P
Thanks for the tip J-P!
David
A: 

I think it would help you

var number = input_string.replace(/\D/g,'');

+1  A: 

var myString="Mode111"; var num =myString.replace(/[a-zA-Z]/g,"");

ritesh choudhary