RegexpGarden




















- Garden Text Representation
12
let garden = "Rose\tRosemary\tRose\tRose\tPrimrose\t
Rose\tRosemary\tRose\tRose\tRosemary";
- Code Editor
- Log
123456
garden = garden
.replace(//gi, "Blackberry");
Lesson task •
Replace with blackberry every rose that is followed directly by rose
Positive lookahead
(?=...)
/x(?=y)/ matches "x" only if it is directly followed by "y"Useful for replacing when you need to conditionally replace some pattern1 witch is followed by another pattern2, and the pattern2 should not be replaced.
For the simple cases where you need to check if the string matches pattern1 followed by pattern2, you can simply write pattern2 after pattern1 in the regular expression - it would be more simple and performant solution with the same result:
1234
console.log(!!"foo42".match(/foo(?=\d*)/gi)) // true
console.log(!!"foo42".match(/foo\d*/gi)) // true
console.log("foo42".replace(/foo(?=\d*)/gi, "bar")) // bar42
console.log("foo42".replace(/foo\d*/gi, "bar")) // bar