2

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

6
  • 2
    str.match(/(\d+)(\D+)/ Commented Dec 2, 2016 at 14:06
  • thanks, seems to do the job Commented Dec 2, 2016 at 14:08
  • Does that mean you need ["10",".cm"]? Commented Dec 2, 2016 at 14:09
  • either will do as i can work with a string once it's split up Commented Dec 2, 2016 at 14:10
  • is it always the same character the string needs to be splitted at? Commented Dec 2, 2016 at 14:11

2 Answers 2

4

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.
Sign up to request clarification or add additional context in comments.

4 Comments

Nice; I got lost in the details, trying to figure out how to make split do the job (which it almost can, but not with javascript regex), and didn't think about just using match instead...
When you need to split so as to keep all the characters there are in the string, matching is most likely what you need. Not always, but in this case, matching is really easier.
how would i write it if i just wanted to keep the decimal with the numbers so "10.10cm" became ["10.10", "cm"]?
There are so many float regexps around here, here is a version I like most /\d*\.?\d+|\D+/g
0

/\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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.