Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Global replace string between tags

Tags:

javascript

Could someone please help me with the regexp javascript code to replace all <br /> tags with a newline "\n" character found within <pre> divisions.. For example, a string passed to the function containing the following:

<pre class="exampleclass">1<br />2<br />3</pre>

Should be returned as (newlines not shown, though I hope you get the idea):

<pre class="exampleclass">1(newline)2(newline)3</pre>

Another example:

<div>foo<br />bar<pre>1<br />2</pre></div>

Returned as:

<div>foo<br />bar<pre>1(newline)2</pre></div>

Note that the class and division content is dynamic, along with other content in the string (other divs etc). On the other hand, the <br /> tag does not change, so there's no need to cater for <br> or other variants.

NB - I'm working with strings, not HTML elements.. Just in case there is any confusion by the way I have presented the question.

like image 392
Graham Avatar asked Oct 12 '25 12:10

Graham


1 Answers

You could use

str.match(/<pre(?:.*?)>(?:.*?)<\/pre>/g);

And then for all matches

replaced = match.replace(/<br \/>/g, '\n');
str.replace(match, replaced);

So probably something like this:

var matches = str.match(/<pre(?:.*?)>(?:.*?)<\/pre>/g),
    len = matches.length,
    i;

for (i = 0; i < len; i++) {
    str = str.replace(matches[i], matches[i].replace(/<br \/>/g, '\n'));
}

EDIT: changed to match <pre class=""> as well.

like image 159
Spiny Norman Avatar answered Oct 14 '25 01:10

Spiny Norman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!