Reputation: 4418
I am trying to match pattern which contains pipe(|) operator.
Have used below code to match patteren
var format = /[ \\|]/; // This is the pattern for matching pipe pattern
if ("Near raghavendra temple ring roads".match(format)) {
alert("Invalid character");
}
"Near raghavendra temple ring roads"
this string does not contains | operator but still above condition getting true.
Not able to to understand what is the mistake in above pattern.
Upvotes: 0
Views: 37
Reputation: 26607
The problem is you have a space in there:
/[ \\|]/
actually means "match any one space, \
or |
".
If all you want to do is match a pipe, then use this:
const format = /[\|]/; // This is the pattern for matching pipe pattern
if ("Near raghavendra temple ring roads".match(format)) {
console.log("Invalid character");
} else {
console.log("Okay");
}
You probably have the double-\
because that's how it needs to appear in strings. However, in regex, if you do two, it makes it a \
literal. If you just want to escape the pipe, just use one.
In fact, in a set like that, you don't even need to escape it:
const format = /[|]/; // This is the pattern for matching pipe pattern
if ("Near raghavendra temple ring roads".match(format)) {
console.log("Invalid character");
} else {
console.log("Okay");
}
if ("Bad | character".match(format)) {
console.log('Bad character');
}
Personally, I like to keep the slash though just for clarity.
Upvotes: 0
Reputation: 2809
var format = /[\\|]/; // This is the pattern for matching pipe pattern
if ("Near raghavendra temple ring roads".match(format))
console.log("Invalid character");
else
console.log('All valid');
You are matching on the space character. Remove the space from the regex pattern (inside the square) brackets
Upvotes: 3