bingjie2680
bingjie2680

Reputation: 7773

Javascript regex escape dot following digits

I would like to test a string which should start with any number of digits but not followed by a dot, so I come up these regs, code in jsfiddle:

var startwith = "some string";
    reg1 = new RegExp("^" + startWith + "[0-9]+(?!\\.)"),
    reg2 = new RegExp("^" + startWith + "\d+(?!\\.)");

var text = "11.1";

console.log(reg1.test(text), reg2.test(text)); // result true, false

I started with reg1, but it fails to return the correct result, so I was just trying the reg2. Surprisingly, the result is correct, but what confuses me is that the two regs return different result, while the patterns are basically equivalent. Anybody have any ideas? all thoughts are appreciated.

Upvotes: 2

Views: 184

Answers (2)

zx81
zx81

Reputation: 41838

Start with any digit not followed by a dot:

if (/^\d(?!\.)/.test(yourString)) {
    // It matches!
} else {
    // Nah, no match...
}

Upvotes: 0

anubhava
anubhava

Reputation: 784998

This should work:

var re = /^\d+(?!\.)\b/;

Problem is that in your regex without word boundary regex matches only first 1 of 11.1 and since next one is not a dot it returns true. You need to force it match till a word boundary is reached.

Online Demo

Upvotes: 1

Related Questions