multiple text search and replace in typescript

To perform multiple text search and replace in TypeScript, you can use regular expressions with the replace function. The regular expression can be created using the RegExp constructor with the g flag, which indicates that the search should be global. Here's an example code snippet:

index.ts
const text = "Hello World, Hello TypeScript!";
const searchTerms = ["Hello", "TypeScript"];
const replaceTerm = "Hi";

const regex = new RegExp(searchTerms.join("|"), "g");
const result = text.replace(regex, replaceTerm);

console.log(result); // "Hi World, Hi Hi!"
266 chars
9 lines

In this example, we have a string text that contains two search terms: "Hello" and "TypeScript". We want to replace both of these terms with the word "Hi". To do this, we create a regular expression using the RegExp constructor and pass it the search terms joined with the | operator. We also include the g flag to indicate that the search should be global. Finally, we call the replace function on the text string with the regular expression and the replace term as arguments.

The resulting string result contains the text with both search terms replaced with the replace term: "Hi World, Hi Hi!".

gistlibby LogSnag