DrStrangeLove
DrStrangeLove

Reputation: 11577

How do i get numbers from this string?

i have this string:

var s = 'http://xxxxxxx.xxx/abcd123456789?abc=1';

how do i get digits 123456789 (between "d" and "?") ?

these digits may vary. the number of digits may vary as well.

How do i get them?? Regex? Which one?

Upvotes: 2

Views: 206

Answers (4)

KooiInc
KooiInc

Reputation: 122986

try

'http://xxxxxxx.xxx/abcd123456789?abc=1'.match(/\d+(?=\?)/)[0];
 //                                             ^1 or more digits followed by '?'

Upvotes: 5

marc
marc

Reputation: 6233

Try

var regexp = /\/abcd(\d+)\?/;
var match = regexp.exec(input);
var number = +match[1];

Upvotes: 1

Aleks G
Aleks G

Reputation: 57346

Yes, regex is the right answer. You'll have something like this:

var s = 'http://xxxxxxx.xxx/abcd123456789?abc=1';
var re = new RegExp('http\:\/\/[^\/]+\/[^\d]*(\d+)\?');
re.exec(s);
var digits = $1;

Upvotes: 0

Kon
Kon

Reputation: 27451

Are the numbers always between "abcd" and "?"?

If so, then you can use substring():

s.substring(s.indexOf('abcd'), s.indexOf('?'))

If not, then you can just loop through character by character and check if it's numeric:

var num = '';

for (var i = 0; i < s.length; i++) {
  var char = s.charAt(i);
  if (!isNaN(char)) {
    num += char;
  }
}

Upvotes: 0

Related Questions