Use replace method with regex to escaping double quotes in JavaScript from a string in a variable.
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.
<!DOCTYPE html>
<html>
<body>
<script>
var str = 'hello "friend" what\'s up?';
console.log(str.replace(/\"/g, '\\"'));
</script>
</body>
</html>
Output:
![JavaScript escape double quotes in a string](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2021/06/JavaScript-escape-double-quotes-in-a-string.jpg?resize=377%2C120&ssl=1)
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version