-1

I was trying to replace the Font color if the string inside was partially matching some condition.

example:

var font_str = "<FONT color='red'>aaa-1/2</br>bbb-1/3</br>aaa-1/20</FONT>"
var match = 'aaa'

if the word before after -x/x was same as the match string, I want to replace the entire word before </br> with black font tag

I was trying to use .replace() and RegExp() but still have no idea how to achieve what I wanted.

font_str.replace(new RegExp(match, "g"), "<FONT face='monospace' color='black'>" + match + "</FONT>")

result:

var font_str = '<FONT color='red'><FONT color='black'>aaa</FONT>-1/2</br>bbb-1/3</br><FONT color='black'>aaa</FONT>-1/20</FONT>'

the output should be:

var font_str = "<FONT color='red'><FONT color='black'>aaa-1/2</FONT></br>bbb-1/3</br><FONT color='black'>aaa-1/20</FONT></FONT>"
Michael M.
  • 10,486
  • 9
  • 18
  • 34
Ripca
  • 29
  • 5

1 Answers1

0

You can use

font_str.replace(
    new RegExp(match.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&') + "(?=[^<]*</?br\\s*/?>)", "g"), 
    "<FONT face='monospace' color='black'>$&</FONT>"
)

See the regex demo.

Details:

  • See Is there a RegExp.escape function in JavaScript?, this escapes the match value
  • See the regex demo. (?=[^<]*</?br\s*/?>) is a positive lookahead that requires zero or more chars other than < + < + an optional / + br + zero or more whitespaces + an optional / + > immediately to the right of the current location.

The $& in the replacement is the match value that was matched (especially useful when you are running a case insensitive regex search).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563