Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - get two numbers from a string

I have a string like:

text-345-3535

The numbers can change. How can I get the two numbers from it and store that into two variables?

like image 774
Alex Avatar asked Aug 26 '10 00:08

Alex


People also ask

How do you split a number in JavaScript?

To do this: Convert the number to a string. Call the split() method on the string to convert it into an array of stringified digits. Call the map() method on this array to convert each string to a number.

How do you find a number in a string?

The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).

What is number () in JavaScript?

Number is a primitive wrapper object used to represent and manipulate numbers like 37 or -9.25 . The Number constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the Number() function.


1 Answers

var str = "text-345-3535"

var arr = str.split(/-/g).slice(1);

Try it out: http://jsfiddle.net/BZgUt/

This will give you an array with the last two number sets.

If you want them in separate variables add this.

var first = arr[0];
var second = arr[1];

Try it out: http://jsfiddle.net/BZgUt/1/


EDIT:

Just for fun, here's another way.

Try it out: http://jsfiddle.net/BZgUt/2/

var str = "text-345-3535",first,second;

str.replace(/(\d+)-(\d+)$/,function(str,p1,p2) {first = p1;second = p2});
like image 190
user113716 Avatar answered Sep 21 '22 00:09

user113716