Showing posts with label Remove "()" Parentheses Quotes (""") from Javascripts string expression. Show all posts
Showing posts with label Remove "()" Parentheses Quotes (""") from Javascripts string expression. Show all posts

Tuesday, June 23, 2020

Remove parentheses, brackets and quotes from string Javascript expression

Remove parentheses, brackets, and quotes from a string

Remove parentheses:

For example: If your result is like:  "{result}"

The below expression will remove the parentheses and give you an answer as "result"

       var value = value.replace(/[\])}[{(]/g, '');
Remove Brackets:

Brackets can be removed from a string in Javascript by using a regular expression in combination with the .replace() method.

var value = value.replace(/[\[\]']+/g, '')

Lets elaborate:
·         The first parameter of.replace() is regular expression /[\])}[{(]/g.
o    Regular expressions are essentially rules used to define a set of characters to match and to subsequently invoke the replace method on.
·         To remove [. and ] individually, we need to escape them using \.
·         + applies the rule to the whole string.

   Remove double quotes:

The below regex for replacing all double-quotes in javascript.  "/g" is for replacing all double quotes in a string.

var value = "result";
value = value.replace(/\"/g, "");  

   Some More Examples with explanations: 

First Regex
x = x.replace(/[{()}]/g, '');
y = y.replace(/[{()}]/g, '');

In first regex /[{()}]/g the outer square brackets [] makes a character class, it will match one of the character specified inside of it. In this case the characters {)}.
Outside of the /regexp/ you have the g (global) modifier meaning that you are entire regular the expression will match as many times as it can, and it will not just make to the first match.

Second regex
x = x.replace(/[\[\]']+/g, '');
y = y.replace(/[\[\]']+/g, '');

In second regex / [\[\]']+/g the outer square brackets [] makes a character class, it will match one of the character specified inside of it. In this case the characters [ ] '.
Note that the square brackets appear scaped inside the [character class] as \ [\].
After it you have specified a + quantifier, it makes the preceding rule match one or more times in a row. Note that this is redundant, even if it works, this is not quite what you want.
Outside of the /regularexpression/ you have the g (global) modifier meaning that your entire regular expression will match as many times as it can, and it will not just make it to the first match.