【问题标题】:JS replace every #word to <div>#word</div> in a stringJS 将字符串中的每个#word 替换为 <div>#word</div>
【发布时间】:2016-08-18 00:57:18
【问题描述】:

我正在创建基于套接字的聊天应用程序。我想更改收到的消息:当消息中的单词包含 # 时,它必须被 div 标签包围。例如'this is #an message' 必须转换为'this is &lt;div&gt;#an&lt;/div&gt; message'。我正在使用 jQuery。

【问题讨论】:

标签: javascript jquery html string replace


【解决方案1】:

这可以通过正则表达式和 javascript 字符串方法来完成。看看这篇文章,它应该提供你需要的一切。 How to replace all occurrences of a string in JavaScript?

【讨论】:

    【解决方案2】:

    您可以像这样使用 RegEX 做到这一点:

    var content="this is #an message";
    alert(content.replace(/(#\S+)/gi,"<div>$1</div>"));

    【讨论】:

      猜你喜欢
      • 2014-08-25
      • 2021-03-21
      • 2011-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 2011-12-08
      相关资源
      最近更新 更多