正则表达式匹配用textarea中的空格填充的行条目

时间:2017-06-10 19:03:50

标签: javascript html regex

我有一个html textarea,其条目可能如下所示:

google.com
   youtube.com   word word
  netflix.com   
 twitch.tv
  vimeo.com  word
soundcloud.com  word    word

我想创建一个功能,在列表中搜索网址并删除它的所有条目。为此,我首先需要一个正则表达式来查找第一个匹配项。请注意,我只需要并且想要找到第一个匹配项。

该功能必须只删除完全匹配。也就是说,

DeleteEntry("youtube.com");

不应删除第二行,但

DeleteEntry("youtube.com   word word");

应。

所以基本上,我需要匹配这种模式

(beginningOfString OR newlineChar) then (anyWhiteSpaceExceptNewline) then (ENTRY) then (anyWhiteSpaceExceptNewline) then (endOfString OR newlineChar)

这是我到目前为止所拥有的

var expression = "\n|^[ \f\r\t\v]*" + entry + "[ \f\r\t\v]*\n|$";
var match = listbox.value.match(expression);

它似乎没有像我期望的那样工作。

1 个答案:

答案 0 :(得分:1)

注意:如果您想在字符串中使用\,则必须将其转义。 "\some text"错误,但"\\some text"是正确的。

var ta = document.getElementById("ta"),
    inp = document.getElementById("inp"),
    btn = document.getElementById("btn");
    
// escape text to be used inside RegeExp (from: https://stackoverflow.com/q/3115150/6647153)
function escape(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

function deleteEntry(query) {
  var text = ta.value;
      
  var regexText = query.trim()                                    // remove surrounding spaces
                       .split(/\s+/)                              // split into tokens ("a   b c" becomes ["a", "b", "c"])
                       .map(escape)                               // escape the tokens ("a.com" becomes "a\\.c" so it'll be /a\.c/ where the '.' is regarded as litteral '.' not as the special character .)
                       .join("\\s+");                             // joins the tokens together with \s+ (["a", "b", "c"] becomes "a\\s+b\\s+c" so it'll be /a\s+b\s+c/)
      
  var regex = new RegExp("^\\s*" + regexText + "\\s*$", "gm");    // surrond regexText with ^\s* and \s*$ and use the g modifier for multiple matches and the m modifier for multiline text
  
  ta.value = text.replace(regex, "");                             // replace the matched text with "" and reassign it back to the textarea
}
    
btn.onclick = function() {
  deleteEntry(inp.value);                                         // calling deleteEntry passing to it the input's value as the query
}
textarea {
  display: block;
  width: 100%;
  height: 100px;
}
<textarea id="ta">
google.com
   youtube.com   word word
  netflix.com   
 twitch.tv
  vimeo.com  word
soundcloud.com  word    word
</textarea>
<input id="inp"><button id="btn">Delete</button>