Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegExp to replace every second asterisk?

I have a string, e.g.:

"The red letters in the following words are suffixes: beauti*ful*, speech*less* and invinc*ible*."

I want to replace the first of each ** pair with <span class='red'> and the second with </span>. I can do this in a for loop, but would like to know how to do it with RegExp.

like image 310
Shoe Avatar asked Feb 17 '26 15:02

Shoe


1 Answers

How about:

s = s.replace(/\*([^*]*)\*/g, "<span class='red'>$1</span>");

\*([^*]*)\* is a little confusing, it searches for:

  • \* - the first asterisk
  • ([^*]*) - the content between the asterisks (captures, so we can replace using $1.
  • \* - the second asterisk

Working example: http://jsbin.com/isufes

like image 52
Kobi Avatar answered Feb 20 '26 03:02

Kobi