Insert HTML into view from AngularJS controller

For Angular 1.x, use ng-bind-html in the HTML: <div ng-bind-html=”thisCanBeusedInsideNgBindHtml”></div> At this point you would get a attempting to use an unsafe value in a safe context error so you need to either use ngSanitize or $sce to resolve that. $sce Use $sce.trustAsHtml() in the controller to convert the html string. $scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml(someHtmlVar); ngSanitize … Read more

Escape string for use in Javascript regex [duplicate]

Short ‘n Sweet (Updated 2021) To escape the RegExp itself: function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, ‘\\$&’); // $& means the whole matched string } To escape a replacement string: function escapeReplacement(string) { return string.replace(/\$/g, ‘$$$$’); } Example All escaped RegExp characters: escapeRegExp(“All of these should be escaped: \ ^ $ * + ? . ( … Read more

Why do backslashes appear twice?

What you are seeing is the representation of my_string created by its __repr__() method. If you print it, you can see that you’ve actually got single backslashes, just as you intended: >>> print(my_string) why\does\it\happen? The string below has three characters in it, not four: >>> ‘a\\b’ ‘a\\b’ >>> len(‘a\\b’) 3 You can get the standard … Read more

Escape a string for a sed replace pattern

Warning: This does not consider newlines. For a more in-depth answer, see this SO-question instead. (Thanks, Ed Morton & Niklas Peter) Note that escaping everything is a bad idea. Sed needs many characters to be escaped to get their special meaning. For example, if you escape a digit in the replacement string, it will turn … Read more

Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]

Expanding on someone else’s answer: <script> var myvar = <?php echo json_encode($myVarValue); ?>; </script> Using json_encode() requires: PHP 5.2.0 or greater $myVarValue encoded as UTF-8 (or US-ASCII, of course) Since UTF-8 supports full Unicode, it should be safe to convert on the fly. Note that because json_encode escapes forward slashes, even a string that contains … Read more

HTML-encoding lost when attribute read from input field

EDIT: This answer was posted a long ago, and the htmlDecode function introduced a XSS vulnerability. It has been modified changing the temporary element from a div to a textarea reducing the XSS chance. But nowadays, I would encourage you to use the DOMParser API as suggested in other anwswer. I use these functions: function … Read more