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

查看:35
本文介绍了如何在 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).

在使用  开关(似乎不起作用)的几个建议之后,我发布了对我的问题的修订解释:

After several proposals to use the  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 = '





2    PC Games        



';
lookup  = lookup.trim() ;
alert(lookup );

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

动线很重要

推荐答案

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

To use a dynamic regular expression see my updated code:

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

你的具体例子是倒退的:

Your specific example is backwards:

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

正则表达式

正则表达式对象

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

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