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. Howe开发者_开发知识库ver, 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?
Try this:
yourstring = yourstring.replace(/'/g, "''")
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
str.replace(/'/g, "''");
Be sure to use the global match flag (g) so that you replace any and all occurrences in the string. More info here.
JS's string.replace uses RegEx
Not necessarily:
var str = "O'Reilly's books";
alert(str.replace("'", "''", 'g'));
MDC's String replace reference:
The pattern can be a string or a RegExp
Mmm, my code above doesn't seem to work on IE6, so that will be:
str.replace(/'/g, "''")
like the others said, but using regexes for such simple operation is overkill.
Try this:
function QuoteEncoding(strvalue) {
var strquotes = /(')/g;
return "'" + strvalue.replace(strquotes, "''") + "'";
}
call this method as follows:
QuoteEncoding(strvalue);
Note that if you don't want to use RegExp (and there are often good reasons not to), the idiom for a simple string replacement is:
str.split("'").join("''")
Although the RegExp version is typically marginally faster, the string version can be a win when you don't know if there might be regex-special characters (like .
) in the search string.
I don't know the exact syntax, but you can find that out yourself:
str.replace(/(?!')'(?!')/g, "''");
Haven't tested this yet, but if it works, it also takes care of only replacing occurances of one single quote in a row. The g modifier is necessary for replacing all ocurrences.
You can use String#replaceAll
.
const str = "'test'";
const replaced = str.replaceAll("'", "''");
console.log(replaced);
js> s = "abc'def'xyz"
abc'def'xyz
js> s.replace(/'/g, "''")
abc''def''xyz
精彩评论