如何使用java脚本在字符串中搜索多个文本? [英] How to search for multiple texts in a string, using java script?

查看:112
本文介绍了如何使用java脚本在字符串中搜索多个文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,要搜索的单词数组:

I have a string, an array of words to be searched for:

strng = "I have been working here since last six months"
text = ["since", "till", "until"]
result = "since"

我想搜索数组中的每个单词,在 strng 中,当在strng中找到任何单词时,它必须是分配给结果。怎么做?

我用 .search()搜索单个单词,但是如何搜索多个单词?请帮助。

我是新手。

I want to search for every word in array, in strng and when any of it is found in the strng, it must be assigned to result. how to do it?
I am using .search() for searching a single word, but how to search for multiple words? please help.
I am a Newbie.

推荐答案

您可以循环使用关键字数组或使用正则表达式。前者很简单,后者更优雅; - )

You can either loop over your array of keywords or use a regular expression. The former is simple, the latter is more elegant ;-)

你的正则表达式应该是/ since | until | until /,但我不是100现在肯定了。如果你打算使用它们,你应该研究一下正则表达式,这里有一个启动器: http:/ /www.w3schools.com/js/js_obj_regexp.asp

Your regex should be something like "/since|till|until/", but I'm not 100% sure right now. You should research a bit about regexes if you're planning to use them, here's a starter: http://www.w3schools.com/js/js_obj_regexp.asp

编辑:试过它并刷新我的记忆。最简单的解决方案是使用.match(),而不是search()。然后就可以归结为单线:

Just tried it and refreshed my memory. The simplest solution is using .match(), not search(). It's boils down to a one-liner then:

strng.match(/since|till|until/) // returns ["since"]

使用.match()为您提供一个包含所有模式的数组,在这种情况下,第一个也是唯一一个匹配是该数组的第一个元素。

Using .match() gives you an array with all occurrences of your pattern, in this case the first and only match is the first element of that array.

这篇关于如何使用java脚本在字符串中搜索多个文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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