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

查看:17
本文介绍了如何使用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|till|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天全站免登陆