Skip to content

Instantly share code, notes, and snippets.

@vbarbarosh
Last active March 30, 2019 19:25
Show Gist options
  • Select an option

  • Save vbarbarosh/31e215c920a3ee88eb04758c0201fff5 to your computer and use it in GitHub Desktop.

Select an option

Save vbarbarosh/31e215c920a3ee88eb04758c0201fff5 to your computer and use it in GitHub Desktop.
js_gotcha_string_replace – Special chars in replacement string https://codescreens.com
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/
// Global_Objects/String/replace#Specifying_a_string_as_a_parameter
// I faced with this problem trying to insert user input into html
// document:
//
// template_html.replace('{{{xxx}}}', html_escape(input))
//
// ls | grep -E '\.(jpg|png|gif)$' original
// ls | grep -E '\.(jpg|png|gif)$' after html escape
// ^^
//
// Instead of seeing the above string in my html, I saw this:
//
// ls | grep -E '\.(jpg|png|gif){{{xxx}}}#39;
// ^^^^^^^^^
//
// I completely forgot about special chars in replacement strings: $$,
// $&, $`, $', $n.
// Using this method you should replace all `$` chars by `$$` in
// replacement strings.
console.log('abc{{{xxx}}}def'.replace('{{{xxx}}}', '--$&--'));
// abc--{{{xxx}}}--def
// This method allows use replacement strings without modifications.
console.log('abc{{{xxx}}}def'.split('{{{xxx}}}').join('--$&--'));
// abc--$&--def
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment