0

I am playing with regular expressions in Javascript and have stumbled across an unexpected behaviour. Take a look: https://jsfiddle.net/ft7h5cw0/

I am trying to replace .html-wrap string in a #my-html-wrapper-random .html-wrap .main-content with #my-html-wrapper-random .html-wrap. For some reason, the result after replacement is:

#my#my-html-wrapper-randomper-random .html-wrap .main-content instead of expeceted #my-html-wrapper-random #my-html-wrapper-random .main-content

What is the reason for this behaviour?

var testString = "#my-html-wrapper-random .html-wrap .main-content";
var rxString = ".html-wrap";
var rx = new RegExp(rxString);
var result = testString.replace(rx,"#my-html-wrapper-random"); // unexpexted result strinf
console.log(result);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
sanjihan
  • 5,592
  • 11
  • 54
  • 119
  • 1
    As Wiktor pointed out, this is a simple mistake. One that you would have spotted if you used a regex tool like [Regex101](https://regex101.com/). In regular expressions, the period means "any character". – Seblor Jul 05 '19 at 08:55
  • 1
    The result is as expected. `.` matches any char but a line break char. Actually, I see no point using this regex, use `var result = testString.replace(".html-wrap", "#my-html-wrapper-random")`. To replace case insensitively and all occurrences, use `var result = testString.replace(new RegExp(rxString.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'gi'), "#my-html-wrapper-random")` – Wiktor Stribiżew Jul 05 '19 at 08:57
  • thanks. For some reason I thought RegExp would handle this by default. stupid me – sanjihan Jul 05 '19 at 08:58

0 Answers0