Reputation: 191
My string:
<h2>headline</h2>
<p>content</p>
<h2>another headline</h2>
<p>another content</p>
I want to replace only the first headline <h2>headline</h2>
with another string.
So far I have str.replace(/<h2>(.*)<\/h2>/, 'another String')
but that replaces <h2>headline</h2><p>content</p><h2>another headline</h2>
because of the second </h2>
.
Is there a way to only replace the first <h2>(.*)<\/h2>
?
Something like: str.replace(/<h2>(.*[except <\/h2>])<\/h2>/, 'another String')
Upvotes: 0
Views: 1021
Reputation: 9647
How about something like this. No jQuery, just native JavaScript.
var s = '<h2>headline</h2><p>content</p><h2>another headline</h2><p>another content</p>'
// Create a holder element and let the document parse our HTML
var el = document.createElement('div')
el.innerHTML = s
// Find and replace what we want
el.querySelectorAll('h2')[0].innerHTML = 'REPLACED'
// Just to output in our snippet
document.querySelectorAll('#init')[0].innerHTML = s
document.querySelectorAll('#res')[0].innerHTML = el.innerHTML
div{border: 1px solid red}
<h3>New HTML</h3>
<div id="res"></div>
<hr>
<h3>Original HTML</h3>
<div id="init"></div>
It's generally a bad idea to use regular expressions for complex structures like HTML. You really want to parse them. That's the idea behind this answer is to leverage the browser (which knows how to parse HTML) to find the element your looking for and work with it.
Upvotes: 0
Reputation: 312
jquery solution will goes like :
e = $j("<div>" + string );
e.find("h2").first().html("any html you want");
e.html()
JS solution will goes like
d = document.createElement ("div");
d.innerHTML = string;
d.querySelector("h2").innerHTML = "any html you want";
d.innerHTML
or simple string operations
var x = string ;
x.substr(0,x.indexOf("<h2>")+4) + "you string " + x.substr(x.indexOf("</h2>")+5)
Upvotes: 0
Reputation: 20750
You can use :first
pseudo selector to change the content of first h2
like following.
$('h2:first').text('another string')
If you want replace the h2
itself then use replaceWith()
method like following.
$('h2:first').replaceWith('another string')
Upvotes: 1
Reputation: 3509
Use the below regex:
str.replace(/<h2>(.*?)<\/h2>/, 'another String')
Quantifier: *? Between zero and unlimited times, as few times as possible,
Upvotes: 0