How do I avoid content that might contain a quote?
I want to record my search terms and pass them to a JavaScript variable, but I don't know how to handle the quotes that might come up.
Here's what I have:
var searchTerms = "<!--#echo var="terms"-->";
var pattern = / /g;
newSearchTerms = searchTerms.replace(/[^a-zA-Z 0-9]+/g,'');
var searchStr=newSearchTerms.replace(pattern,"_");
I am concerned that "terms" contain double quotes (or apostrophy if I use single quotes in JS) then my function will fail.
How do I escape the line before it gets into the script?
Thanks
Steve
Edit / answer: I ended up with this by moving it into an external script that grabbed and parsed the request rather than replaying it in HTML.
source to share
If terms
contains quotes, by the time you are done var searchTerms = "<!--#echo var="terms"-->";
it is too late to replace the quotes, your JavaScript will be invalid. For example, if Itterms
contains "terms" , your JavaScript will look like this (and throw a syntax error in the browser):
var searchTerms = "These are the "terms"";
If you are sure it terms
only contains double quotes, you can do:
var searchTerms = '<!--#echo var="terms"-->';
If it can contain both single quotes and double quotes, then you need to flush the output on the server using a server side technology more complex than <!--#echo var="..."-->
.
source to share
From your code, it looks like you are using Apache SSI. echo
SSI has an attribute encoding
that will allow you to specify url-style encoding. You can encode quotes this way and just unencode in Javascript withunescape()
Try the following:
var terms = "<!--#echo encoding="url" var="terms"-->";
terms = unescape(terms)
source to share