ElSajko
ElSajko

Reputation: 1640

Regex, two ways, different results.

Here goes two same ways to achive something. They both should do the same thing, but they don't.

Code: http://jsfiddle.net/8vjctofs/

a1 = function(str) {
    return str.replace(new RegExp("[^a-zA-Z0-9\s]", "gi"), "");
}

a2 = function(str) {
    return str.replace(/[^a-zA-Z0-9\s]/gi, "");
}

var string = "abc abc";
console.log(a1(string));
console.log(a2(string));

output:

abcabc
abc abc

Please, tell me why? Code is the same, except that first function creates regex, by new operator, second not.

Upvotes: 2

Views: 44

Answers (2)

Ry-
Ry-

Reputation: 224913

> console.log("[^a-zA-Z0-9\s]");
"[^a-zA-Z0-9s]"

String literals also use backslashes as escapes, and unrecognized sequences have their backslashes ignored. The escape never makes it to the RegExp constructor.

The correct way to do things, of course, is to always use regular expression literals. If you need a literal backslash in any string, though, it can be escaped too.

new RegExp("[^a-zA-Z0-9\\s]", "gi")

Upvotes: 2

anubhava
anubhava

Reputation: 785156

You need to use \\s while using RegExp object:

a1 = function(str) {
    return str.replace(new RegExp("[^a-zA-Z0-9\\s]", "gi"), "");
}

Otherwise \s is interpreted as literal s in RegExp object.

Upvotes: 2

Related Questions