Reputation: 221
I am in client side context. I have this html:
<p>Text text \n other text </p>
I want to match only \n element inside paragraph, and replace only this with "br" tag.
I want to do this only inside tag "p" and for all match.
I supposed to use regex in javascript.
Thanks and sorry for my bad english.
Upvotes: 2
Views: 277
Reputation: 8902
You can use a for
loop with getElementsByTagName
:
for(i = 0; i < window.document.getElementsByTagName("p").length; i++){
window.document.getElementsByTagName("p")[i].innerHTML = window.document.getElementsByTagName("p")[i].innerHTML.replace(/\\n/g, "<br/>");
}
If this is inside a string and not inside the HTML, you can add it to a <div>
element while handling it like this:
var myString = "<p>Text text \n other text </p>";
var div = document.createElement("div");
div.innerHTML = myString;
for(i = 0; i < div.getElementsByTagName("p").length; i++){
div.getElementsByTagName("p")[i].innerHTML = div.getElementsByTagName("p")[i].innerHTML.replace(/\\n/g, "<br/>");
}
myString = div.innerHTML;
Upvotes: 0
Reputation: 115262
Use html()
method with callback and inside callback replace text using String#replace
method.
$('p').html(function(i, htm) {
return htm.replace(/\\n/g, '<br>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text text \n other text</p>
UPDATE 1 : If it's a string then use String#replace
method.
console.log(
'<p>Text text \n other text</p>'.replace(/\n/g, '<br>')
)
UPDATE 2 : If the string contains other tag element and you just want to update the p
tag then do something like.
var str = '<p>Text text \n other text</p>';
console.log(
// create a temporary div eleemnt
$('<div>', {
// set html content from string
html: str
})
// get all p tags
.find('p')
// iterate and replace \n
.html(function(i, htm) {
// replace \n with br tag
return htm.replace(/\n/g, '<br>')
})
// back to the temp div
.end()
// get it's updated html content
.html()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
UPDATE 3 : With pure JavaScript by generating a temporary DOM element.
var str = '<p>Text text \n other text</p>';
// create a temporary div element
var div = document.createElement('div');
// set html content form string
div.innerHTML = str;
// get all p tags and convert into Array using Array.from
// for older browser use [].sclice.call instead
Array.from(div.getElementsByTagName('p'))
// iterate over p tags
.forEach(function(el) {
// update the html content
el.innerHTML = el.innerHTML.replace(/\n/g, '<br>')
});
// get updated html content
console.log(div.innerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 3