-2

Hi I want to insert additional character on strings from "replace" function.

example

string = "AGAS Ranges"
find = "gas"

my code

string.toLowerCase().replace("gas", `<b>${find}</b>`)

i want the result is like this, only add b and /b tag from the character you are looking for without changing the original words
"A<b>GAS</b> Ranges"


Thanks
  • [`String.prototype.replace()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace): _"The `replace()` method **returns a new string** with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If pattern is a string, only the first occurrence will be replaced. **The original string is left unchanged**."_ – Andreas Aug 07 '20 at 14:08

1 Answers1

2

The pattern can be a RegExp, so you can reference to first matched group like $1.

i modifier - makes the regex case insensitive.

console.log("AGAS Ranges".replace(/(gas)/i, "<b>$1</b>"))

Use a variable in a regular expression:

const string = 'AGAS Ranges';
const find = 'gas';
const regExp = new RegExp(`(${find})`, 'i');

console.log(string.replace(regExp, '<b>$1</b>'));
Nikita Madeev
  • 3,563
  • 4
  • 12