0

I have

"id": 1468306 

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

plrthink
  • 311
  • 1
  • 3
  • 13

7 Answers7

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

Will be your number if you have that in a String.

mdenton8
  • 619
  • 5
  • 13
0

You can use this regex:

/: (\d+)/

as in:

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

Output:

1468306

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

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
Mr. B.
  • 8,041
  • 14
  • 67
  • 117
  • Where are you getting the idea that it's JSON? And why do you think `parseInt` would work here? – user2736012 Sep 08 '13 at 03:55
  • The first example will set `numbers` to an array containing one element: the string `'1468306'`. That it appears to be the number `1468306` is an artifact of how `alert` works. – Ted Hopp Sep 08 '13 at 03:57
  • @user2736012 because it looks like a JSON string. It doesn't have to, but could be and it would be too bad if he would try to get the contents by regEx instead of the simple parsing. You're right about parseInt. – Mr. B. Sep 08 '13 at 04:00
  • @TedHopp good advice, but he asked for a regEx to separate the numbers from the string. If he needs the numbers for calculating, he could/should parse it to a number. – Mr. B. Sep 08 '13 at 04:03
0

you can use parseInt() method in javascript as follows:

var str = parseInt(id);
UVM
  • 9,776
  • 6
  • 41
  • 66
0

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.

Chirag Rupani
  • 1,675
  • 1
  • 17
  • 37
0

This will match in this cases

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

 /id\s?[:]\s?[0-9]+/g.match(stringhere)
Misters
  • 1,337
  • 2
  • 16
  • 29
0

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/

mdenton8
  • 619
  • 5
  • 13