Reputation: 1653
In form there is a text field in which I want to restrict '^' sign. I am trying to escape carret sign '^' in regular expression. For e.g.
"abcdef".match([^])
is returning true
please provide suggestion.
Upvotes: 0
Views: 100
Reputation: 5822
If you just want to check if the string contains a caret try
/\^/.test( "abcdef" ); // => false
/\^/.test( "^abcdef" ); // => true
/[^\^]/.test( "aslkfdjfs" ); // =>true as caret does not exist in string
Upvotes: 0
Reputation: 2067
Use .search(/\^/)
.Backslash '\' will remove the function of '^' .This way you can restrict.
Upvotes: 1
Reputation: 72279
To match the line beginning:
> 'abcdef'.match(/^/)
[ '', index: 0, input: 'abcdef' ]
To match literal ^
, escape it:
> 'abcdef'.match(/\^/)
null
To match literal ^
inside a class of characters, put it on any position except the first:
> 'abcdef'.match(/[xyz^]/)
null
> 'abcdef'.match(/[def^]/)
[ 'd', index: 3, input: 'abcdef' ]
Upvotes: 3
Reputation: 26951
Syntax error. Regexes must be enclosed in /
in JS, so it should be
"abcdef".match("/[^]/"); //gives null
Also, you don't need to embrace the /
into a []
, you can just escape it with \
:
"abcdef".match("/\^/"); //gives null
See the http://www.regular-expressions.info/javascript.html for details
Upvotes: 0