简体   繁体   中英

Wrap next text in a tag

Is there any dynamic way to wrap next text.

<p>Enterprise integration platform</p>

Expected output:

<p>Enterprise <span>integration</span> platform</p>

I need to wrap any text which will appear after 'Enterprise'

This code will find all occurrences of paragraphs with the word Enterprise in them. You will need more processing if the word can occur after other words

 $("p:contains('Enterprise')").html(function() { var texts = this.textContent.split(" "); return texts.shift()+" <span>"+texts.shift()+"</span> "+texts.join(" "); }); 
 span { color:red } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <p>Some stuff:</p> <p>Enterprise integration platform</p> <p>Enterprise architecture</p> <p>Enterprise service as a service</p> 

 var elements = document.querySelectorAll("p"); for (var i = 0; i < elements.length; i++) { var element = elements[i]; element.innerHTML = element.innerText.replace(/Enterprise (\\S+)/, "Enterprise <span>$1</span>"); } 
 /* just style to highlight span */ span { background-color: red; } 
 <p>Enterprise integration platform</p> 

Note that this regular expression will replace only first occurrence of Enterprise , if you need replace all occurrences you need to add g suffix: /Enterprise (\\S+)/g .

I'm using regular expression here, I can explain it here

  • Enterprise — obviously search for Enterprise text.
  • \\S+ — search for one or more non-whitespace characters.
  • (\\S+) — capture this non-whitespace character group to replace using $1 .

If need case-insensitive search for Enterprise you should rewrite replacing operator to .replace(/(enterprise) (\\S+)/i, "$1 <span>$2</span>") .

Note that I'm using i suffix for case-insensitive search and capturing enterprise word because it can be in any case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM