Javascript - get two numbers from a string

I have a line like:

text-345-3535 

Rooms are subject to change. How can I get two numbers from it and store it in two variables?

+7
javascript jquery string
source share
5 answers
 var str = "text-345-3535" var arr = str.split(/-/g).slice(1); 

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

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

If you want them to add this in separate variables.

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

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


EDIT:

Just for fun, it's different here.

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

 var str = "text-345-3535",first,second; str.replace(/(\d+)-(\d+)$/,function(str,p1,p2) {first = p1;second = p2}); 
+6
source share
 var m = "text-345-3535".match(/.*?-(\d+)-(\d+)/); 

m [1] will contain "345", and m [2] will have "3535"

+3
source share

If you're not used to regular expressions, @patrick dw's answer is probably better for you, but this should work too:

 var strSource = "text-123-4567"; var rxNumbers = /\b(\d{3})-(\d{4})\b/ var arrMatches = rxNumbers.exec(strSource); var strFirstCluster, strSecondCluster; if (arrMatches) { strFirstCluster = arrMatches[1]; strSecondCluster = arrMatches[2]; } 

This will extract the numbers if it is exactly three digits, followed by a dash, followed by four digits. An expression can be modified in many ways to get exactly the string you are using.

+2
source share

Try this, var text = "text-123-4567";

 if(text.match(/-([0-9]+)-([0-9]+)/)) { var x = Text.match(/([0-9]+)-([0-9]+)/); alert(x[0]); alert(x[1]); alert(x[2]); } 

Thanks.

+2
source share

Another way to do this (using a string tokenizer).

 int idx=0; int tokenCount; String words[]=new String [500]; String message="text-345-3535"; StringTokenizer st=new StringTokenizer(message,"-"); tokenCount=st.countTokens(); System.out.println("Number of tokens = " + tokenCount); while (st.hasMoreTokens()) // is there stuff to get? {words[idx]=st.nextToken(); idx++;} for (idx=0;idx<tokenCount; idx++) {System.out.println(words[idx]);} } 

Exit

words [0] => text
words [1] => 345
words [2] => 3535

+2
source share

All Articles