Javascript正则表达式或函数匹配整个单词 [英] Javascript regex or function to match whole word

查看:134
本文介绍了Javascript正则表达式或函数匹配整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



任何人都可以为下面提到的场景提供JavaScript功能或Regexp。



例如:我的字符串是:

1)' My String abc-s '。



我有一些项目来匹配上面字符串中的单词。

 var items = [abc,def,ghi]; 



如果上面的字符串包含任何数组项,那么它必须返回true。

在上面的项目数组中不包含'abc',所以它必须返回false。





2)

 var items = [abc-s,def -s,ghi-s]; 



如果上面的字符串包含上述任何项目,则必须返回true。 / pre> 



我尝试过:



大家好,

任何人都可以为下面提到的场景提供JavaScript函数或Regexp。

例如:我的字符串是:
1)' My String abc-s '。

我有一系列与上述字符串中的单词匹配的项目。
< pre> var items = [abc,def,ghi];



如果上面的字符串包含任何数组项然后它必须返回true。

在上面的项目数组中不包含'abc',所以它必须返回false。





2)

 var items = [abc-s,def-s,ghi-s]; 



如果上面的字符串包含上述任何项目,那么它必须返回true。

解决方案

\b - 表示单词的开头或结尾,因此您可以创建如下表达式

(\babc \b | \ bdef \b | \ bhgi \ b)



您可以在 Scriptular - Javascript Regular Expression Editor [ ^ ]


查看此内容:

 // var str =My String abc; 
var str =My String abc-s;

var items = [abc,def,ghi];
// var items = [abc-s,def-s,ghi-s];

for(i = 0; i< items.length; i ++){
var pattern = new RegExp((< = \\\\ | \\ b) )+ items [i] +(?= [] \\b | \\ | |


));
alert(pattern.test(str));
}

请参阅演示: JSFiddle [ ^ ]


Hi Everyone,

Can any one please provide a JavaScript function or Regexp for the below mentioned scenario.

For Example: my string is :
1) 'My String abc-s'.

I have array of items to match the word in the above string.

var items= ["abc", "def", "ghi"];


If the above string contains any of the array item then it has to return true.
In the above array of items not contain 'abc', so it has to return false.


2)

var items= ["abc-s", "def-s", "ghi-s"];


If the above string contains any of the above item then it has to return true.



What I have tried:

Hi Everyone,

Can any one please provide a JavaScript function or Regexp for the below mentioned scenario.

For Example: my string is : 
1)  'My String abc-s'.

I have array of items to match the word in the above string.
<pre>var items= ["abc", "def", "ghi"];


If the above string contains any of the array item then it has to return true.
In the above array of items not contain 'abc', so it has to return false.


2)

var items= ["abc-s", "def-s", "ghi-s"];


If the above string contains any of the above item then it has to return true.

解决方案

\b - indicates beginning or end of word, so you could create expression like below
(\babc\b|\bdef\b|\bhgi\b)

you could try it online at Scriptular - Javascript Regular Expression Editor[^]


Check this out:

//var str = "My String abc";
var str = "My String abc-s";

var items= ["abc", "def", "ghi"];
//var items = ["abc-s", "def-s", "ghi-s"];

for (i=0; i < items.length; i++){
  var pattern = new RegExp("(<=\\s|\\b)"+ items[i] +"(?=[]\\b|\\s|


)"); alert(pattern.test(str)); }

See demo at: JSFiddle[^]


这篇关于Javascript正则表达式或函数匹配整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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