[英]Regex word boundary (backspace) test case
I want to test this condition if the key event is backspace or not: 如果按键事件是否为退格键,我想测试这种情况:
if (key.match(/[\b]/)) {
return true;
}
where key
is coming from keystroke. key
来自击键。 (like 'a', '6' , '.'
etc) What should be the value of key
for if
condition to return true
? (如
'a', '6' , '.'
等等)应该是什么的价值key
的if
条件返回true
?
I tried key
as '.'
我尝试将
key
为'.'
since it is a word boundary (But only with a word, sadly). 因为它是一个单词边界(可悲的是,只有一个单词)。 What should be the key to show
backspace <-
. 显示
backspace <-
的关键是什么?
[\\b]
matches a backspace character since \\b
is inside a character class. [\\b]
与退格字符匹配,因为\\b
在字符类内部。 To match a word boundary, use /\\b/
(where \\b
is not inside a character class): 要匹配单词边界,请使用
/\\b/
(其中\\b
不在字符类内):
var key = "a"; if (/\\b/.test(key)) { // Or, perhaps, for better portability, /[\\x08]/.test(key) alert(true); }
If you plan to match all non-word characters you just need \\W
, not \\b
. 如果计划匹配所有非单词字符,则只需要
\\W
,而不需要\\b
。 The word boundary \\b
matches a position between ^
and \\w
or \\w
and $
, or \\W
and \\w
or \\w
and \\W
(where \\w
stands for a [a-zA-Z0-9_]
and \\W
stands for any other character not inside these ranges). 单词边界
\\b
与^
和\\w
或\\w
和$
或\\W
和\\w
或\\w
和\\W
之间的位置匹配(其中\\w
代表[a-zA-Z0-9_]
和\\W
代表不在这些范围内的任何其他字符)。 Also, if you need to match a 1-char string, do not forget anchors: /^\\W$/
. 另外,如果您需要匹配1个字符的字符串,请不要忘记定位符:
/^\\W$/
。
UPDATE UPDATE
To test a backspace key, you can use 要测试退格键,可以使用
var key = "\\x08"; if (/[\\b]/.test(key)) { alert(true); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.