[英]Search a regular expression for a word
I'm trying to make something where a user can type in a string, !exchange
and then a word after. 我正在尝试使用户可以在其中输入字符串,
!exchange
,然后再输入一个单词。 If the word after exchange matches the word huntsman, for example, I want it to do one thing, and another thing for a different word. 例如,如果交换后的单词与huntsman单词匹配,我希望它做一件事情,而对另一个单词做另一件事。
I've tried to do 我试着做
var req = msg.match(/^!exchange/i); //msg is the string that I'm testing
But that doesn't work. 但这是行不通的。 I've also tried
我也尝试过
var req = msg.match(/^!exchange \b/i);
But I get the same result. 但我得到相同的结果。 Can anyone help?
有人可以帮忙吗?
To get the word after !exchange
, use a capture group: 要获得
!exchange
之后的单词,请使用捕获组:
/^!exchange\s+(\w+)/i
Now req[1]
will contain the word after !exchange
. 现在
req[1]
将包含!exchange
之后的单词。
function doit(input) { var msg = input.value; var req = msg.match(/^!exchange\\s+(\\w+)/i); if (req) { document.getElementById("result").textContent = req[1]; } }
<input type="text" id="input" onchange="doit(this)"> <br>Word is <span id="result"></span>
It sounds like you want something like this: 听起来您想要这样的东西:
var msg = "!exchange apple"; msg.match(/^!exchange (.*)/i);
(which returns ["!exchange apple", "apple"]
) (返回
["!exchange apple", "apple"]
)
String.match() returns an array of the original string, followed by any matching groups. String.match()返回原始字符串的数组,后跟任何匹配的组。 You'll need to match each word after "!exchange" as a group to get them back in the array.
您需要将“!exchange”之后的每个单词作为一个组进行匹配,以使它们重新回到数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.