在正则表达式中删除插入符号'^'

时间:2012-11-22 12:22:11

标签: javascript regex

在表单中有一个文本字段,我想在其中限制'^'符号。 我试图在正则表达式中逃避carret标志'^'。 对于例如

"abcdef".match([^])正在返回

请提供建议。

4 个答案:

答案 0 :(得分:3)

匹配开头的行:

> 'abcdef'.match(/^/)
[ '', index: 0, input: 'abcdef' ]

要匹配文字^,请将其转义:

> 'abcdef'.match(/\^/)
null

要在一个字符类中匹配文字^,请将其放在除第一个字符之外的任何位置:

> 'abcdef'.match(/[xyz^]/)
null
> 'abcdef'.match(/[def^]/)
[ 'd', index: 3, input: 'abcdef' ]

答案 1 :(得分:1)

使用.search(/\^/) .Backslash'\'将删除'^'的功能。这样你可以限制。

答案 2 :(得分:0)

语法错误。正则表达式必须包含在JS的/中,所以它应该

"abcdef".match("/[^]/"); //gives null

此外,您无需将/包含在[]中,只需使用\即可将其撤消:

"abcdef".match("/\^/"); //gives null

有关详细信息,请参阅http://www.regular-expressions.info/javascript.html

答案 3 :(得分:0)

如果您只想检查字符串是否包含插入符号,请尝试

/\^/.test( "abcdef" ); // => false
/\^/.test( "^abcdef" ); // => true
/[^\^]/.test( "aslkfdjfs" ); // =>true as caret does not exist in string
相关问题