Lets say there is a string in javascript:
const str = 'some th.in.g';
const input = 'thing';
the input
variable is dynamic and might have a different value on runtime. So need to write a regex that will replace the input in the str
, but the problem is that along with having to write a regex with dynamic variable, also want to ignore certain character when matching, like in this case it’s a .
character. So the end result would be after replacing the string as follows:
const replacedString = some <span>th.in.g</span>;
so basically want to wrap the matched word with HTML span tag, but alongside want to ignore some character in order have a match for replacing.
So far we have achieved to wrap the matched word in HTML but ignoring any specified character is remaining:
const searchText = 'thing';
const result = 'some th.in.g';
const regex1 = new RegExp(this.searchText, 'gi');
const finalText = result.replace(regex1, '<span class="highlighted">$&</span>');
may Allah guide us all!