I'm replacing t
by g
when t
is not followed by the letter p
using this line of code:
"tpto".replace(/(t)[^p]/g, "g");
However, the result is tpg
and I was expecting tpgo
. As I don't know which letter will follow the t
I need something dynamic but I don't know what to do, any ideas?
The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.
3.1 The difference between replaceAll() and replace()If search argument is a string, replaceAll() replaces all occurrences of search with replaceWith , while replace() only the first occurence. If search argument is a non-global regular expression, then replaceAll() throws a TypeError exception.
Note: If count is not specified, the replace() method replaces all occurrences of the old substring with the new substring.
replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Syntax : string.replace(old, new, count)
You can use negative lookahead assertion:
"tpto".replace(/t(?!p)/g, "g");
// => "tpgo"
/t(?!p)/
: t
will match only if it is not (negative) followed (lookahead) by p
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With