Categories
JavaScript Answers

How to escape single quotes in JavaScript string for JavaScript evaluation?

Spread the love

To escape single quotes in JavaScript string for JavaScript evaluation, we use the string replace method.

For instance, we write

const escaped = searchKeyword.replace(/'/g, "\\'");

to call replace with the regex for single quotes and a string for the escaped single quotes to replace the single quotes in searchKeyword with the escaped version and return the escaped string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *