Last active
March 30, 2019 19:25
-
-
Save vbarbarosh/31e215c920a3ee88eb04758c0201fff5 to your computer and use it in GitHub Desktop.
js_gotcha_string_replace – Special chars in replacement string https://codescreens.com
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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