【问题标题】:Removing lines containing specific words in javascript在javascript中删除包含特定单词的行
【发布时间】:2023-03-24 18:33:02
【问题描述】:

这个脚本应该获取一个链接列表,通过更改一些单词来转换一些链接,并删除包含特定字符串的其他链接。

第一部分还可以。我需要第二个帮助。线

    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>

【问题讨论】:

  • 所以你想删除其中包含category 的行?

标签: javascript


【解决方案1】:

我认为您需要转义正斜杠,因为您还将它们用作正则表达式分隔符。

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

【讨论】:

    【解决方案2】:

    假设您要复制&lt;p&gt; 中的这些行,请删除其中包含类别的行。

    把你的函数改成

    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>" );
    }
    

    【讨论】:

    • 有效!但是你最后忘了改变变量。我们发送给 p 而不是 x 的是“行”。谢谢。
    • @NachtundNebel 进行了更改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 2021-03-19
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    相关资源
    最近更新 更多