简体   繁体   中英

Get substring after first digit occurrence in Javascript

I am trying to extract the characters after(and include) the first digit:

ABC 123SD => 123SD
123 => 123
123SD => 123SD
ABC =>

My current solution is following,

var string1 = ABC 123SD;
var firstDigit = string1.match(/\d/);
var result = string1.slice($string.indexOf(firstDigit), 0);

Use a regular expression.

 var string = 'ABC 123SD'; var match = string.match(/\\d.*/); var result = match ? match[0] : ''; console.log(result); 

\\d matches the first digit, and .* matches everything after it.

You can just remove all leading characters that aren't digits, eg

 function strip(s) { return s.replace(/^\\D*/,''); } // Example ['ABC 123SD', '123', '123SD', 'ABC'].forEach(s => console.log(s + ' => ' + strip(s))); 

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