How to control "and" when declaring a variable in a javascript file

I have a search box and the user can put the search text in it. Example: book, "book", "book". And in the js file, the variable gets the value from the search box.

var searchtext= "${searchtext}"; <br/>

      

This code failed if the user put "book" in the search box. Since this time

var searchtext= ""book"".

      

If i change

var searchtext= "${searchtext}";  to var searchtext= '${searchtext}';

      

This code failed if the user put "book" in the search box. Please help me, thanks!

+3


source to share


3 answers


You can replace "

or '

one quote '

. Here's an example:

var str= '"book"'; 
str.replace(/["|']+/g, "'");

      



Demo: jsFiddle

+2


source


It would be easier for you if you did not allow the user to insert special characters in the search box.



$('searchBoxElement').bind('keypress', function (event) {
    var regex = new RegExp("^[a-zA-Z0-9]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
      event.preventDefault();
      return false;
    }
});

      

0


source


A quick dirty fix

str.replace(/["|']+/g, "'");
var searchtext= "${searchtext}"; 

      

-1


source







All Articles