简体   繁体   中英

jquery span after first space

I have three words I would like to add a span around the content after the first space so

hello world

becomes:

hello <span>world</span>

and:

hello world again

becomes:

hello <span>world again</span>

Here is my JavaScript code:

 $( "#main-nav li a" ).each(function( index ) {
   $(this).html( $(this).text().replace(/([\S]*)\s(.*)/, "$1 <span>$2</span>") );
}); 

You can do it with some regex:

text = text.replace(/([\S]*)\s(.*)/, "$1 <span>$2</span>");

If text is hello world , the above code will convert it to hello <span>world</span>

Maybe more understandable (for me for sure),

  1. use find method on whitespace character, get first position in string.
  2. get first substring, from index 0 to the specific position.
  3. get substring from specific position to string.length and wrap them
  4. merge both strings one more time.

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