treeseal7
treeseal7

Reputation: 749

split javascript string using a regexp to separate numbers from other characters

so for example:

"10.cm" ...becomes... [10,".cm"] or ["10",".cm"], either will do as I can work with a string once it's split up.

i tried

"10.cm".split(/[0-9]/|/[abc]/)

but it seems that i don't have such a great understanding of using regexp's

thanks

Upvotes: 2

Views: 630

Answers (2)

Sefa_Kurtuldu
Sefa_Kurtuldu

Reputation: 24

/\W/ Matches any non-word character. This includes spaces and punctuation, but not underscores. In this solution can be used /\W/ with split and join methods. You can separate numbers from other characters.

let s = "10.cm";
console.log(s.split(/\W/).join(" "));

output = 10 cm

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You may tokenize the string into digits and non-digits with /\d+|\D+/g regex:

var s = "10.cm";
console.log(s.match(/\d+|\D+/g));

Details:

  • \d+ - matches 1 or more digits
  • | - or
  • \D+ - matches 1 or more characters other than digits.

Upvotes: 4

Related Questions