Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using replace() replaces too much content

I'm replacing t by gwhen 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?

like image 809
Armand Grillet Avatar asked Jun 28 '15 09:06

Armand Grillet


People also ask

What does the replace () method do?

The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.

Does replace replace all occurrences?

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.

Does replace in Python replace all?

Note: If count is not specified, the replace() method replaces all occurrences of the old substring with the new substring.

What does replace () mean in Python?

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)


1 Answers

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.
like image 69
falsetru Avatar answered Oct 20 '22 08:10

falsetru