How to remove backslashes (\) and quotation marks (") from a string?

1

I would like to prevent the use of these characters in a string. I think the most elegant way would be by regular expression, but I do not understand anything about how to put one together.

A replace would also help.

    
asked by anonymous 06.08.2014 / 15:08

2 answers

5

To test whether a string has \ or " you can do this:

/[\"]/g.test('Olá\ bom dia'); // dá true
/[\"]/g.test('Olá "bom dia"'); // dá true
/[\"]/g.test('Olá bom dia'); // dá false

To test you can use this in the console of this page:

var st = $('#question-header a').text();
/[\"]/g.test(st); // true

In the regex I used [\"] and the modifier "g" that serves more than one occurrence. If you just want to know "whether there is or not" you can take it. Straight parentheses create a list of characters to look for, and dento has the bar (which has to be escaped, hence 2), and the quotation marks.

To remove these characters , you can do this:

string.replace(/[\"]/g, '');

If you want to test with the console of this page paste it into the console:

$('#question-header a').text().replace(/[\"]/g, '')
    
06.08.2014 / 15:22
0

You can use replace ():

str.replace('Item a ser removido', "O que sera colocado no lugar");

In your case:

str.replace('"', ""); //para remover a (")
str.replace('\', ""); //para remover a (\)
    
06.08.2014 / 16:46