Using jquery or JS, how do you turn a string into a link?

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 pass the word hello to a link using jquery.

 <p>This is some copy. In this copy is the word <a href="">hello</a></p> 

This in itself is not too complicated. My problem is if the word is already separated from the link as shown below ...

 <p>In this copy is the <a href="">word hello</a></p> 

I do not want this to end with a link in a link ...

 <p>In this copy is the <a href="">word <a href="">hello</a></a></p> 

Any help would be greatly appreciated.

+6
source share
9 answers

A small 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 regular expression

 $(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/

+2
source

You can do it this way

Live demo

 $('p').each(function(){ if($(this).find('a').length > 0) return; lastSpaceIndex = $(this).text().lastIndexOf(' '); if(lastSpaceIndex == -1) lastSpaceIndex = 0; WordToReplace = $(this).text().substring(lastSpaceIndex); idx = $(this).text().lastIndexOf(WordToReplace); resultstring = $(this).text().substring(0, idx); $(this).html(resultstring); $(this).append($( "<a href='#'>" + WordToReplace + "</a>")); });​ 
+1
source

This jQuery solution looks for a specific term and does not create a link if it finds it, followed by a closing link tag.

 var searchTerm = "hello"; $('p:contains("' + searchTerm + '")').each(function(){ var searchString = $(this).html(); var searchIndex = searchString.indexOf(searchTerm); var startString = searchString.substr(0 , searchIndex); var endString = searchString.substr(searchIndex + searchTerm.length); if(endString.match(/<\/a>/g)) return; $(this).html(startString + "<a href=''>" + searchTerm + "</a>" + endString); });​ 

Here is the link for jsfiddle for her.

+1
source

Wrote a simple function to check if replacement text is enclosed with a link tag. See below,

DEMO: http://jsfiddle.net/wyUYb/4/

 function changeToLink (sel, txt) { var regEx = new RegExp(txt, 'g'); $.each($(sel), function (i, el) { var linkHTML = $(el).html(); var idx = linkHTML.indexOf(txt); if (idx >= 0) { var t = linkHTML.substring(idx); //Fix for IE returning tag names in upper case http://stackoverflow.com/questions/2873326/convert-html-tag-to-lowercase t = t.replace(/<\/?[AZ]+.*?>/g, function (m) { return m.toLowerCase(); }) var closingA = t.indexOf('</a>'); t = t.substring(0, closingA); if (closingA != -1) { t = t.substring(0, closingA); if (t.indexOf('<a') < txt.length) { return; } } linkHTML = linkHTML.replace(regEx, '<a href="">' + txt + '</a>'); $(el).html(linkHTML); } }); } 

Also, if you add a sublink, your browser will simply change it to two links. Maybe because using nested links is impractical. See below,

Also registered with W3C for Nested Links

12.2.2 Nested links are illegal

The relationships and bindings defined by element A must not be nested; A element must not contain any other elements of A.

Because the DTD defines a LINK element as empty, LINK elements may not be nested.

And that’s why the browser treats the sublink as separate links.

http://jsfiddle.net/H44jE/

Look at the control panel at the bottom right of the image.

enter image description here

+1
source

Can you check the parent of a word before turning it into a link?

 if (parent != 'a') { // do your thing } 

(I don't know what the actual jQuery would have to check)

EDIT

The following will replace the word in all <p> elements that DO NOT contain a link in them.

It may not work as required, but I hope it will show you the direction

 // get all p elements that contain the word hello but DO NOT have link in them var elems = $('p:contains("hello")').not(':has(a)'); // replace instances of hello in the selected p elements $(elems).html($(elems).html().replace(/(hello)/g,'<a href="new">$1</a>')); 

Live Demo on JSBin

0
source

Try the user .replace jquery function something like this:

 var str = $('p').html().replace('(some)','(to some)'); 
0
source

You need jquery: not a selector, or .not ().

This is good in API docs, you can select your content and then deselect links within it.

http://api.jquery.com/not-selector/

0
source

Instead of searching for the word and searching for its parent, find the link and check the word contained in it:

 if($('a').text() === "hello"){ //already linked }else{ //not linked } 
0
source

First save the words, getting rid of the current anchor tag, if any:

 $('a').each(function() { $(this).replaceWith(this.childNodes); }); 

Then replace the line you need to work with

 $('p').html($('p').text().replace('hello', '<a href="">hello</a>')); 
0
source

Source: https://habr.com/ru/post/927361/


All Articles