0

I have a value "4.66lb"

and i want to separate "4.66" and "lb" using regex.

I tried the below code, but that separates only number "4,66"!! but i want both the values 4.66 and lb.

var text = "4.66lb";
var regex = /(\d+)/g;
alert(text.match(/(\d+)/g));
1
  • Have you tried appending ([a-z]+) ? Commented Jun 24, 2014 at 7:07

3 Answers 3

2

Have a try with:

var res = text.match(/(\d+(?:\.\d+)?)(\D+)/);

res[1] contains 4.66
res[2] contains lb

In order to match also 4/5lb, you could use:

var res = text.match(/(\d+(?:[.\/]\d+)?)(\D+)/);
Sign up to request clarification or add additional context in comments.

3 Comments

Short and sweet, +1. :)
Hey, i have one more scenario where the number can be 4/5lb, so in this case i need to split 4/5 and lb....so what would be the regex for this?
@user3770003: replace the dot by a slash: /(\d+(?:\/\d+)?)(\D+)/
0

You could use a character class also,

> var res = text.match(/([0-9\.]+)(\w+)/);
undefined
> res[1]
'4.66'
> res[2]
'lb'

Comments

0

Let me explain with an example

var str = ' 1 ab 2 bc 4 dd';   //sample string

str.split(/\s+\d+\s+/)
result_1 = ["", "ab", "bc", "dd"]  //regex not enclosed in parenthesis () will split string on the basis of match expression

str.split(/(\s+\d+\s+)/)        //regex enclosed in parenthesis () along with above results, it also finds all matching strings
result_2 = ["", " 1 ", "ab", " 2 ", "bc", " 4 ", "dd"] 

//here we received two type of results: result_1 (split of string based on regex) and those matching the regex itself

//Yours case is the second one
//enclose the desired regex in parenthesis
solution : str.split(/(\d+\.*\d+[^\D])/)

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.