How to remove backslashes ( ) and quotes (") from a string?

Asked

Viewed 25,883 times

3

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 don’t understand anything about putting together a.

A replace would also help.

  • Can be more specific and give an example where you have a "" in a string?

  • It was a very specific case where a user registered information in the spreadsheet with this bar there. When I was importing it was a mistake. It seems it was a typo, but I must warn you.

2 answers

10


To test if a string has \ or " can do so:

/[\\"]/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 on the console of this page:

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

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

To remove these characters, can do so:

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

If you want to test with the console of this page do this on the console:

$('#question-header a').text().replace(/[\\"]/g, '')
  • Using lists is very advantageous not to have to escape the escape that is escaping another escape ( \\ ). ^_^

  • Sergio did not understand how I can use this expression to actually remove the characters. Can help me?

  • 2

    @Joaopaulo, my distraction, I did not see that I wanted to remove! You can do so: string.replace(/[\\"]/g, '') I’ll edit in response

  • 1

    @Joaopaulo Dai, to remove just use the method replace with this Regex for '' and maintain the /g to replace all occurrences

  • @Sergio, to replace a bar "" by two " ", as it would be?

  • @Joaopaulo can put here the example of what he wants to do?

  • When you send js via ajax pro controller of C# it gives an error in a string in this format: "C: Documents Photo.jpg". To get around this error I want to replace the string to "C: Documents Photos photo.jpg" pro controller accept.

  • @Joaopaulo you are wearing JSON.stringify to escape these characters? this should solve the problem.

Show 3 more comments

0

Voce 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 (\)
  • 1

    Why are you removing two " instead of just one? And the backslash needs to escape in the string, the way it is is is a syntax error (try).

  • This method only removes one occurrence, for more occurrences it is best to use global regex

Browser other questions tagged

You are not signed in. Login or sign up in order to post.