如何在JavaScript中匹配整个单词? [英] How can I match a whole word in JavaScript?

查看:76
本文介绍了如何在JavaScript中匹配整个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过文本框搜索整个单词.假设我搜索我",我应该找到所有出现的单词我".在本文中,但不是"memmm".每说一遍.

I am trying to search a single whole word through a textbox. Say I search "me", I should find all occurrences of the word "me" in the text, but not "memmm" per say.

我正在使用JavaScript的search('my regex expression')执行当前搜索(没有成功).

I am using JavaScript's search('my regex expression') to perform the current search (with no success).

在使用了\b开关的一些建议(似乎无效)之后,我发布了关于我的问题的修订说明:

After several proposals to use the \b switches (which don't seem to work) I am posting a revised explanation of my problem:

由于某种原因,这似乎无法解决问题.假设以下JavaScript搜索文本:

For some reason this doesn't seem to do the trick. Assume the following JavaScript search text:

var lookup = '\n\n\n\n\n\n2    PC Games        \n\n\n\n';
lookup  = lookup.trim() ;
alert(lookup );

var tttt = 'tttt';
alert((/\b(lookup)\b/g).test(2));

移动线条是必不可少的

推荐答案

要使用动态正则表达式,请参见我更新的代码:

To use a dynamic regular expression see my updated code:

new RegExp("\\b" + lookup + "\\b").test(textbox.value)

您的具体示例倒退:

alert((/\b(2)\b/g).test(lookup));

正则表达式

正则表达式对象

这篇关于如何在JavaScript中匹配整个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆