4

How to split and select which is number using regex. User can enter string like:

1dozen 3 dozen dozen1 <= unlikely but assume user will type that too

30/kg

I still find out with the incomplete one:

/[a-z](?=\d)|\d(?=[a-z])/i

But missing space and forward slash. Can anyone help me?

1
  • If the user only enters number plus text then parseInt(str,10) will do the job Commented Oct 22, 2011 at 5:06

2 Answers 2

12

The lookarounds are completely unnecessary here!

See http://jsfiddle.net/5WJ9v/

The code:

var text = "1dozen 3 dozen dozen1 30/kg";
var regex = /(\d+\.|\d+)+/g;
alert(text.match(regex));

You get a match object with all of your numbers.

The script above correctly alerts 1,3,1,30.

Sign up to request clarification or add additional context in comments.

Comments

2
var str = '1dozen 3 dozen dozen1 30/kg';
str.match(/\d+/g); // ["1", "3", "1", "30"]

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.