【问题标题】:adding span tag with new id before each round bracket在每个圆括号之前添加带有新 id 的 span 标签
【发布时间】:2023-03-09 08:02:01
【问题描述】:

我有一些像诗句引用的文本,我需要在每个圆括号之前自动添加一个跨度标签(当访问页面时)和一个新的 id。

输入:

<p>some text (Jn 1:2), more text sentences (Gn 5-12, 23 ref) and more etc.</p>

输出:

<p>some text <span id="1">(Jn 1:2)</span>, more text sdfkljgdf <span id="2">(Gn 5-12, 23)</span> and more etc.</p>

因此它会在每个圆括号 ( ) 周围添加 span 标签,即使它们不在同一行中(如果结束 ) 在代码的另一行中)。

我尝试了以下类似的方法.. 我愿意接受任何使用 php 或 Javascript 的东西..

var myString_before = str.split("(")[count];
//alert (myString_before);

//get all text before )
var myString_after = myString_before.split(")")[0];
alert(" ref: " + myString_after);

if (x != true) {
    $('span').each(function (k) {
        var replace_str = $(this).html().replace(/\(/g, '<div 
        style="display: inline" id= "' + pos + '">(</div>');
        $(this).html(replace_str);
    })
}
x = document.getElementsByTagName('div')[count].hasAttribute("style");

【问题讨论】:

    标签: javascript php html tags prepend


    【解决方案1】:

    您可以混合使用 jQuery 的 .html()String.replace

    let i = 0;
    $('p').html((_, oldHtml) => 
      oldHtml.replace(/\([^)]+\)/g, match => `<span id="${++i}">${match}</span>`)
    );
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>some text (Jn 1:2), more text sentences (Gn 5-12, 23 ref) and more etc.</p>

    (正则表达式只匹配括号之间的任何内容,包括它们。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      • 1970-01-01
      相关资源
      最近更新 更多