删除包含javascript中特定单词的行

时间:2016-05-05 10:40:48

标签: javascript

此脚本应该采用链接列表,通过更改某些单词来转换一些链接,并消除包含特定字符串的其他单词。

第一部分没问题。我需要帮助第二个。这条线

    x = x.replace(/^.+/category/.+$/mg, "");
即使我们用*更改+,

也不起作用。我在这里使用了来源(1& 2)。所以,帮助菜鸟。

<!DOCTYPE html>
<html>
<body>

<h3>Instert your links</h3>

input:<br>
<textarea id="myTextarea">
http://example.com/ad/123.html
http://example.com/ad/345.html
http://example.com/ad/3567.html
http://example.com/category/fashion.html
http://example.com/ad/8910.html
http://example.com/category/sports.html



</textarea>



<button type="button" onclick="myFunction()">Get clean links</button>

<p id="links"></p>

<script>
function myFunction() {
        x = document.getElementById("myTextarea").value;
        x = x.replace(/http:\/\/example.com\/ad\//g, "http://example./com/story/"); 
        x = x.replace(/\n/g,"</br>");
        x = x.replace(/^.+/category/.+$/mg, "");
    document.getElementById("links").innerHTML = x;
}
</script>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

我认为你需要逃避正斜杠,因为你也将它们用作正则表达式分隔符。

x = x.replace(/^.+\/category\/.+$/mg, "");

答案 1 :(得分:1)

假设您要在<p>中删除包含类别的行中的这些行。

将您的功能更改为

function myFunction() {
  x = document.getElementById("myTextarea").value;
  var lines = x.split("\n").filter( function(val){ 
    return val.indexOf( "category" ) == -1;
  });
  document.getElementById("links").innerHTML = lines.join( "<br>" );
}
相关问题