【问题标题】:how to replace specific text wrapping characters with span tags?如何用 span 标签替换特定的文本环绕字符?
【发布时间】:2018-10-13 06:28:36
【问题描述】:

期望的行为

::text:: 替换为<span>text</span>

例如,给定一个字符串:

Here is a ::test span:: and another ::span::, colons in this context eg: 
http://somelink.com are not effected.  

如何将:: 字符替换为打开和关闭<span> 标记,如下所示:

Here is a <span>test span</span> and another <span>span</span>, colons 
in this context eg: http://somelink.com are not effected.  

我的尝试

我实际上是在尝试复制以下行为:

https://www.npmjs.com/package/markdown-it-span

一个非常有用的插件markdown-it parser,因为它似乎有一个错误(我无法弄清楚如何修复),它一直是discussed in an issue here

代码中存在导致创建 span 标签两次的错误。

::spanned:: => <span><span>spanned</span></span>

另外,像http: 这样的输入会被转换成http::

编辑:

我刚刚在这里遇到了类似的问题,可能有答案...

Replace all content between characters with JavaScript

【问题讨论】:

    标签: javascript regex markdown-it


    【解决方案1】:

    使用正则表达式/::([^::]+)::/g,这似乎很简单:

    var s = 'Here is a ::test span:: and another ::span::, colons in this context eg: http://somelink.com are not effected.';
    
    console.log(s.replace(/::([^::]+)::/g, "<span>$1</span>"));

    【讨论】:

    • 但是我觉得:这个角色应该被转义,我错了吗?
    【解决方案2】:

    这很简单。这个对我有用:(::)([\w\s]+)(::) 将其替换为 &lt;span&gt;$2&lt;/span&gt;

    ::text::    => <span>text</span>
    ::spanned:: => <span>spanned</span>
    
    
    Here is a ::test span:: and another ::span::, colons in this context eg: 
    http://somelink.com are not effected.  
    => 
    Here is a <span>test span</span> and another <span>span</span>, colons in this 
    context eg: 
    http://somelink.com are not effected.
    

    【讨论】:

      猜你喜欢
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 2014-05-08
      • 2021-04-05
      • 2019-01-23
      相关资源
      最近更新 更多