remove a substring from a string in typescript

To remove a substring from a string in TypeScript, you can use the replace() method with a regular expression that matches the substring you want to remove. Here's an example:

index.ts
const str = "hello world";
const subStr = "world";
const result = str.replace(new RegExp(subStr, 'g'), '');
console.log(result); // Output: "hello "
149 chars
5 lines

In the code above, we use the replace() method to replace all occurrences of the subStr with an empty string. We create a new regular expression object using the RegExp constructor, which takes two arguments: the substring that we want to replace, and the 'g' flag, which means that we want to replace all occurrences of the substring, not just the first one.

The replace() method returns a new string with the substring removed, which we then log to the console.

Note that the above code will remove all occurrences of the substring. If you only want to remove the first occurrence, you can remove the 'g' flag from the regular expression:

index.ts
const str = "hello world";
const subStr = "world";
const result = str.replace(new RegExp(subStr), '');
console.log(result); // Output: "hello world"
149 chars
5 lines

gistlibby LogSnag