【问题标题】:Jquery replace all strings starting with # and add linkJquery替换所有以#开头的字符串并添加链接
【发布时间】:2011-11-08 20:16:17
【问题描述】:

我在留言板上有一个大块或文本,其中包含以# 开头的字符串。我可以使用 jquery 将这些替换为包含字符串的链接吗?

例如,改变:

<div id="mydiv">This is my #block of text with #multiple hash strings</div>

到:

<div id="mydiv">This is my <a href="newpage.asp?block">#block</a> of text with <a href="newpage.asp?multiple">#multiple</a> hash strings</div>

提前致谢!

【问题讨论】:

    标签: jquery str-replace


    【解决方案1】:

    您可以使用以下代码来替换字符串:

    var string = "#has etc #has ";
    string = string.replace(/#(\S+)/g, '<a href="newpage.asp?$1">#$1</a>');
    

    【讨论】:

      【解决方案2】:

      这将完成工作:

      $('*:contains("#")').each(function(){
       if($(this).children().length < 1) 
            $(this).html( 
                 $(this).text().replace(
                      /#(.*)#/
                      ,'<a href=newpage.asp?'+$(this).text()+'>'+$(this).text()+'</a>'
                 )  
             ) 
      });
      

      【讨论】:

      • 欢迎来到 StackOverflow!在发布之前测试您的解决方案总是一个好主意,可能在 jsfiddle.net 上,以确保它们确实按预期工作。
      • 当您使用text()html() 替换内容时,您应该注意。如果html中包含&amp;gt;script&amp;lt;,替换后的结果为&lt;script&gt;
      • 感谢@RobW 提供>脚本< html()也会发生效果吗?刚试了一下,好像还可以。 jsfiddle.net/bobney/4tKn3
      • @Bobney 您的代码根本不起作用,因为 div 元素包含一个子元素。即使您只使用.html(),代码也容易出错:&lt;a style="color:#000"&gt;Color&lt;/a&gt; 会中断。
      • @RobW 啊,你没看错。会去玩。感谢您让我走上正确的道路。
      猜你喜欢
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 2023-01-07
      相关资源
      最近更新 更多