Reputation: 6012
Is it possible to add formatting to html using JS (what can easily be done in Office editors)?
This is what I want to do:
let htmString = "<p>baz foobar</p><p>foo<i>bar</i></p>";
let reg = RegExp( "^fooba", "g" );
let htmModified = myFunction( htmString, reg, ["<u>", "<\/u>"] );
console.log( htmModified );
Output:
<p>baz foobar</p><p><u>foo</u><i><u>ba</u>r<i/></p>
(being after <p>
is interpreted as the beginning of a line, thus only the 2nd foobar
matches /^/)
Upvotes: 0
Views: 63
Reputation: 18990
This can be easily done using CSS (or alternatively XPath) selectors and some JavaScript. To make things even easier, throw jQuery into the mix, to get access to methods like .wrapInner
.
$("p:nth-child(2)").wrapInner("<u></u>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<test>
<p>baz foobar</p><p>foo<i>bar</i></p>
</test>
and here is an example using a CSS query selector in vanilla JS:
var wrapper = document.createElement("u");
var parent = document.querySelector("p:nth-child(2)");
var div = parent.appendChild(wrapper);
while(parent.firstChild !== wrapper)
wrapper.appendChild(parent.firstChild);
<p>baz foobar</p><p>foo<i>bar</i></p>
To get up to speed, here is a nice intro on that matter: JavaScript HTML DOM
and here is a very nice and playful introduction to CSS selectors: CSS Diner.
Regarding your specific request, if you insist on using regex here is an attempt to
To make things a little more interesting, I search for a substring that does not start a position 0 of the selected text from the HTML fragment. Simply change the regex pattern or pass 0 as start index to the CustomWrapper
function, if you like.
function CustomWrapper(ele, start, end, wrapper) {
var len = ele.html().length;
var selectedText = ele.html().substring(start, end);
var replacement = '<'+wrapper+'>'+selectedText+'</'+wrapper+'>';
ele.html(ele.html().substring(0, start) + replacement + ele.html().substring(end, len));
}
var secondEle = $("p:nth-child(2)");
console.log(secondEle.html());
var re = /<i>ba/g;
match = re.exec(secondEle.html());
console.log(match.index + '-' + re.lastIndex);
CustomWrapper(secondEle, match.index, re.lastIndex, 'u');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<test>
<p>baz foobar</p><p>foo<i>bar</i></p>
</test>
This sample contains a lot of nuts and bolts. Please ask if you need an explanation for something specific.
Upvotes: 2