Javascript正则表达式或函数匹配整个单词

编程入门 行业动态 更新时间:2024-10-11 23:21:42
本文介绍了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正则表达式或函数匹配整个单词

本文发布于:2023-11-02 12:07:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552354.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单词   函数   正则表达式   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!