jamesandersen/string-replace-webpack-plugin

Plugin matches nothing if pattern has double quotes

SijanC147 opened this issue · 1 comments

I'm trying to append an arbitrary path to all of my html href attributes. The plugin matches and replaces everything correctly up until i include the double quotation marks in my pattern. So i've tested the following:

/href/ig (works)
/href=/ig (works)
/href="/ig (nope.)
/href=\"/ig (neither.)

I also tried all of the above using the constructor new RegExp() method, but results remained the same.

Am i missing something here? I don't know that double quotes need to be escaped in regex.

Just figured out what was going on, for anyone who experiences anything similar..

My config passed forward the html content string from webpack's html-loader, after inspecting this string I noticed that all double quotation marks where automatically being escaped as ", this means that when trying to match against a double quotation mark using this plugin you have to take into account this backslash, so finally the configuration that worked:

/href=\"/ig

Naturally, if you intend to replace matches with a string that also contains a double quotation mark, ideally you maintain the escaped structure from html-loader, so:

return "href=\\\"otherstuffhere";

or i guess you could use one less backslash if you return the string in single quotation marks,

return 'href=\\"otherstuffhere';

Hopefully this saves anyone in a similar situation some time.