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
No comments:
Post a Comment