0

I am having a tricky time getting this regular expression to work. The pattern I have so far is:

var dollarPattern = /^\d{1,}|\s\d/gi;

var matchedResults = new Array();
matchedResults = textValue.match(dollarPattern);

What I am hoping to achieve is using the example string "2 to 2.99 (63 items)", I want to check if it either starts with a digit, or if it contains a blankspace followed by a digit (in this case, both conditions are true). However, I keep getting a "matchedResults is null" error in Firefox (although it should have a length of 2).

Any ideas what I am doing wrong? Thanks...

2
  • 3
    What else is going on around that code? Commented May 12, 2011 at 7:04
  • {1,} is equivalent to +. That makes it a bit shorter and more readable. Commented May 12, 2011 at 7:08

2 Answers 2

2

All you need is escaping.

// Please note that this works, but @Lekensteyn pointed out that this uses string literals
// Also, this will give you the first match(if exists) only.
alert("2 to 3.99 (63 items)".match("^\\d\|\\s\\d"));

OR

// This one will give you all possible matches
alert("2 to 3.99 (63 items)".match(/^\d|\s\d/g));
Sign up to request clarification or add additional context in comments.

2 Comments

Do you understand RE's? There is no need to use string literals instead of regular expression literals.
@Lekensteyn Nope, not a 100%. I posted the answer because it worked. There is no "need" but that doesn't mean that it can't be used and it won't work if used, right? After your comment, I did search for Javascript RE basics and I have modified the answer. Anyway, thanks for my very first downvote. :-)
0

Works fine in Chrome, FF4, and IE8.

I get null when I puts quotes around the regex.

However, the output I get it "2, 2".

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.