开发者

javascript - get two numbers from a string

开发者 https://www.devze.com 2023-01-13 07:12 出处:网络
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?var str = \"text-345-3535\"

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?


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});


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

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


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号