7

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?

5 Answers 5

6
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});
Sign up to request clarification or add additional context in comments.

Comments

3
var m = "text-345-3535".match(/.*?-(\d+)-(\d+)/);

m[1] will hold "345" and m[2] will have "3535"

Comments

2

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

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. The expression can be modified in many ways to retrieve exactly the string you are after.

Comments

2

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.

Comments

2

Another way to do this (using 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]);}
}

output

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.