2

I'm not so bad in regular expression but there I have a tiny problem, maybe one of you can answer this simple question.

I do this:

var myString = "10px";
var myRegexp = new RegExp("(\\d*\\.?\\d*){1}(em|ex|grad|ch|deg|ms|rad|rem|s|turn|vh|vw|vmin|vmax|px|cm|in|pt|pc|%)?", "gi");

myString.replace(myRegexp, function( match, number, type ){
    console.log(match, number, type);
});

The replace console log two time, the first is : "10px", "10", "px" and I don't know why there is a second time, it return me that: ,,undefined (the two first value are not null or empty string, they return just nothing, absolutely empty).

My question, why the replace try a seconde replacing on nothing ? And how avoid it ?

1
  • Minor thing: {1} is completely pointless Commented Mar 27, 2014 at 10:25

2 Answers 2

3

Instead of:

 (\\d*\\.?\\d*){1}

Use start anchor:

^(\\d*\\.?\\d*)

As your regex has everything optional and matches empty string also.

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

4 Comments

Yes this solve the problem but if value is .5, the regexp dont match.
I find another solution, but the start anchor look better, it is (\\d*\\.\\d*|\\.)...
@anubhava I believe the OP wants to always match a number. Your proposal will match an empty line
Nothing ! Your answer is good, the problem is my example, I said "10px". It is only cause of the start anchor cant find 10px in "translateX(10px)", I did not think well before asking the question, I can't replace nothing by something, so the answer of Ron is better for avoiding any other problem. The solution is to do not search nothing. :)
1

I think it is because your expression has everything optional, so you are also matching a zero-length string (an issue with javascript). If I understand what you want to do, I don't think the number has to be optional, so you could try:

(\d*\.?\d+)(em|ex|grad|ch|deg|ms|rad|rem|s|turn|vh|vw|vmin|vmax|px|cm|in|pt|pc|%)?

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.