简体   繁体   中英

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?

try

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

Try

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

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

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;

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