Tutorial :Split a string in jquery



Question:

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...


Solution:1

Try this:

var num = parseInt(myString.match(/\d+/)[0]);  


Solution:2

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


Solution:3

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.


Solution:4

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).


Solution:5

var str = 'Mode123';  var num = str.match(/\d/g).join('');  

or

var num = str.replace(/\D/g,'');  


Solution:6

I think it would help you

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »