I have some text with something like verse references, that I need to add a span tag automatically (when the page is accessed) with an new id before each round bracket.
Input:
<p>some text (Jn 1:2), more text sentences (Gn 5-12, 23 ref) and more etc.</p>
Output:
<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>
So it adds the span tag around each round brackets ( )
even if they are not in the same line (if the closing )
is in another line of the code).
I tried something like the following.. and I am open for anything that works using php or 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");
You can use a mix of jQuery's .html()
and 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>
(The regexp simply matches anything between parentheses, including them.)