简体   繁体   中英

Get a substring before the first figure in javascript

I'm trying to extract all the text until the first figure that appears. Let's say I have this kind of string "Paris 01 Louvre" . I would like to have only "Paris" or if I've "Neuilly sur Seine 03 bla blab" I want to extract "Neuilly sur Seine" .

I'm struggling with regex in javascript but I can't find the right formula.

"Neuilly sur Seine 03 bla blab".match(/^\D+(?=\s)/);
// => Neuilly sur Seine

This answer also ensures trailing whitespace isn't captured.

basic regular expression:

var re = /^([^\d]+)\s/;    
var str = "Neuilly sur Seine 03 bla blab";
console.log( str.match(re) );

^(.+?)\\d

That grabs everything before the first digit ( \\d ). Play with the regex here .

Anything but a number:

^[^0-9]*
  • ^ is the start-of-line
  • [] indicates a character class
  • ^ inside the character class means "invert this class"
  • 0-9 is the numbers 0 to 9, so [^0-9] means any character besides 0 to 9
  • * is "zero or more" of the character/class which it follows

这会从字符串的开头抓取所有不是数字的东西。

s.match(/^\D*/)

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