2015-04-03 71 views
0

我想让用户可以在其中输入一个字符串,!exchange然后输入一个单词。例如,如果交换后的单词匹配huntsman这个词,我希望它做一件事,另一件事用于另一个单词。搜索一个词的正则表达式

我试图做

var req = msg.match(/^!exchange/i); //msg is the string that I'm testing 

但是,这并不工作。我也试过

var req = msg.match(/^!exchange \b/i); 

但是我得到了同样的结果。谁能帮忙?

+3

什么是 “不工作” 是什么意思?请明确点。 – 2015-04-03 23:25:08

+0

By not does not work,I mean that match method does not find a match for!exchange in msg string。 – dragonbanshee 2015-04-03 23:26:31

+0

如果'!exchange'是字符串中的第一个单词,则应该找到它,否则,如果它可以位于msg字符串中的任何位置 - 删除'^'。 – sinisake 2015-04-03 23:27:09

回答

2

!exchange后得到了这个词,用一个捕获组:

/^!exchange\s+(\w+)/i 

现在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>

0

这听起来像你想是这样的:

var msg = "!exchange apple"; msg.match(/^!exchange (.*)/i);

(返回["!exchange apple", "apple"]

String.match()返回原始字符串数组,然后任何匹配的组。您需要将“!exchange”之后的每个单词作为一个组来匹配,以将它们返回到数组中。