我可以将此搜索短语实现为Javascript正则表达式

时间:2015-11-24 22:29:31

标签: javascript regex

我在文字输入框中有以下搜索词组

"phrase one" "phrase two" one two

我希望以下列格式将搜索短语发送到服务器

|phrase one|phrase two|one|two

我可以使用正则表达式替换搜索字符串开头和结尾的|,但我很难完成剩下的工作。

在英语中,这将是搜索

phrase one OR phrase two OR one OR two

正则表达式就像

replace " with |
replace space with | for a phrase not in quotes ("") 

我正在使用Javascript。

1 个答案:

答案 0 :(得分:1)

使用此正则表达式:

(?:"[^"]+"|\w+)

解释

(?:             # one of the alternations
    "           # starting with quotes
    [^"]+       # a sequence of not quotes
    "           # the closing quotes
|               # OR
    \w+         # a word sequence
)               #

Regex live here.

var string = '"phrase one" "phrase two" one two'; // textbox input

var answer = ''; // starts empty


string.replace(/(?:"[^"]+"|\w+)/g, function (match) {

  answer += '|' + match.match(/[^"]+/)[0];
  // foreach match add one pipe '|' and the value without quotes to answer

});

answer = answer.slice(1);

document.write(answer); // the message you want send to server

希望它有所帮助。

相关问题