简体   繁体   中英

how to get numbers from a string in javascript?

I have

"id": 1468306 

inside of a string, how can I use regular expression to get the number 1468306 for it?

JSON.parse("{" + yourString + "}").id

如果您的字符串中有数字,将是您的数字。

You can use this regex:

/: (\d+)/

as in:

s = '"id": 1468306';
r = /: (\d+)/;
console.log(r.exec(s)[1]);

Output:

1468306

Fiddle: http://jsfiddle.net/SfeMh/

var regEx   = /\d+/g;
var str = '"id": 1468306';
var numbers = str.match(regEx);
alert(numbers); // returns 1468306

It looks like you're trying to parse a JSON String. Try this way as already mentioned:

var parsedObj = JSON.parse(myJSONString);
alert(parsedObj.id); // returns 1468306

您可以在javascript中使用parseInt()方法,如下所示:

var str = parseInt(id);

Following code may help you:

var input = '"id": 1468306';
var matches = input.match(/"id": (\d+)/);
var id = matches[1];

The id get the required number.

This will match in this cases

id : 156454;
id :156454;
id:156454;

 /id\s?[:]\s?[0-9]+/g.match(stringhere)

Alright, my JSON answer still stands, use it if that's your full string you're giving us in the question. But if you really want a regex, here's one that will search for "id" and then find the number after.

parseInt(yourString.match(/("id"\s?:\s?)(\d+)/)[2])

Fiddle: http://jsfiddle.net/tS9M4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM