So I have a piece of HTML that looks something like this...
<p>This is some copy. In this copy is the word hello</p>
I want to turn the word hello into a link using jquery.
<p>This is some copy. In this copy is the word <a href="">hello</a></p>
That in itself is not too hard. My problem is that if the word is already apart of a link like the example below...
<p>In this copy is the <a href="">word hello</a></p>
I don't want that to end up with a link within a link...
<p>In this copy is the <a href="">word <a href="">hello</a></a></p>
Any help would be much appreciated.
JavaScript Code: ready(function(){ $('#button1'). click(function(){ $(". link"). attr('href','https://www.w3resource.com/'); }); });
JavaScript String link() String link() is deprecated in JavaScript. Avoid using it. It may cease to work in your browser at any time. The link() method returns a string embedded in an <a> tag: <a href="url">string</a>
In JavaScript, link() is a string method that is used to create the HTML <a> element with a hyperlink.
A little regex should do the trick (Update, see below):
$(document).ready(function(){
var needle = 'hello';
$('p').each(function(){
var me = $(this),
txt = me.html(),
found = me.find(needle).length;
if (found != -1) {
txt = txt.replace(/(hello)(?!.*?<\/a>)/gi, '<a href="">$1</a>');
me.html(txt);
}
});
});
Fiddle: http://jsfiddle.net/G8rKw/
Edit: This version works better:
$(document).ready(function() {
var needle = 'hello';
$('p').each(function() {
var me = $(this),
txt = me.html(),
found = me.find(needle).length;
if (found != -1) {
txt = txt.replace(/(hello)(?![^(<a.*?>).]*?<\/a>)/gi, '<a href="">$1</a>');
me.html(txt);
}
});
});
Fiddle: http://jsfiddle.net/G8rKw/3/
Edit again: This time, "hello" is passed as a variable to the regex
$(document).ready(function() {
var needle = 'hello';
$('p').each(function() {
var me = $(this),
txt = me.html(),
found = me.find(needle).length,
regex = new RegExp('(' + needle + ')(?![^(<a.*?>).]*?<\/a>)','gi');
if (found != -1) {
txt = txt.replace(regex, '<a href="">$1</a>');
me.html(txt);
}
});
});
Fiddle: http://jsfiddle.net/webrocker/MtM3s/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With