Skip to content

How to replace the string from any specific word till end of the string through regex?

I wanna replace the string-specific word till the end of the string through regex but got nothing as the desired output.

String: Parameter: Input: 'Hello', code: 81279

After using the described regex I got the following output.

string.replace(/(code:).+?((?=",)|(?="}))/gi, '').

Output: Parameter: Input: 'Hello', code: 81279

Expected Output: Parameter: Input: 'Hello',

Answer

Your regex searches for strings ending with either ", or "}. You can just remove ((?=",)|(?="})), use a non-lazy operator and search for spaces in front of code:

const string = "Parameter: Input: 'Hello', code: 81279";
console.log(string.replace(/ *code:.+/gi, ''));