Friday, December 10, 2010

Insert Backslash Before a Double Quote

Sometimes, you need to dynamically write html text from JavaScript. If the text contains a combination of single and double quotes, you may run into problems. Here is a simple function to avoid those problems.
function insertBackslashBeforeDoubleQuote(str){
 var reg = /"/g;
 var newstr = '\\"';
 return str.replace(reg,newstr);
}
As you see, the function uses a RegExp object on the first line to look for a double quote:
reg = /"/g;
 
The second line defines our replacement string - \"
The backslash in front of the quote has to be escaped with another backslash.
newstr = '\\"';
The last line searches the string and if a double quote is found it is replaced by our newstr pattern.
return str.replace(reg,newstr);
Here is a similar function that inserts a backslash before a single quote if it is contained in the string argument.
function insertBackslashBeforeSingleQuote(str){
 var reg = /'/g;
 var newstr = "\\'"
 return str.replace(reg,newstr);
}


Some other posts:

A JavaScript endsWith function

Highlight HTML Table Rows with JavaScript