Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for replacing a single-quote with two single-quotes

I'm running into an issue that I think is being caused by needing to double-up on some single quotes inside a string. However, JS's string.replace uses RegEx, and I've never built a RegEx by hand.

Can someone help me build a RegEx to find a single quote and replace it with two single quotes?

like image 269
Adam V Avatar asked Oct 22 '09 21:10

Adam V


People also ask

How do you replace single quotes with double quotes?

Use the String. replace() method to replace double with single quotes, e.g. const replaced = str. replace(/"/g, "'"); . The replace method will return a new string where all occurrences of double quotes are replaced with single quotes.

How do you replace double quotes in regex?

To remove double quotes just from the beginning and end of the String, we can use a more specific regular expression: String result = input. replaceAll("^\"|\"$", ""); After executing this example, occurrences of double quotes at the beginning or at end of the String will be replaced by empty strings.

Are single and double quotes interchangeable?

In HTML, CSS and JavaScript code, single and double quotes are interchangeable.

How do you replace a single quote in a string?

Use the String. replace() method to replace single with double quotes, e.g. const replaced = str. replace(/'/g, " ); . The replace method will return a new string where all occurrences of single quotes are replaced with double quotes.


2 Answers

Try this:

yourstring = yourstring.replace(/'/g, "''") 
like image 54
Rubens Farias Avatar answered Sep 19 '22 17:09

Rubens Farias


You don't need to use RegExp.

String patterm version:

str.replace("'", "''", 'g') 

RegExp pattern version:

str.replace(/'/g, "''") 

Here you have some useful RegExp links:

  • RegExp Tutorial
  • Regular Expression Basic Syntax Reference
  • RegExp Build&Testing Online Tool
like image 23
rogal111 Avatar answered Sep 21 '22 17:09

rogal111