Can't replace "[" and "]" characters in a string in Javascript - javascript

I'm trying to replace "[" and "]" characters in the string using javascript.
when I'm doing
newString = oldString.replace("[]", "");
then it works fine - but the problem is I have a lot of this characters in my string and I need to replace all of the occurrences.
But when I'm doing:
newString = oldString.replace(/[]/g, "");
or
newString = oldString.replace(/([])/g, "");
nothing is happens. I've also tried with HTML numbers like
newString = oldString.replace(/[]/g, "");
but it doesn't work neither. Any ideas how to make it?

You either need to escape the opening square bracket, and add a pipe between them:
newString = oldString.replace(/\[|]/g, "");
Or you need to add them in a character class (square brackets) and escape them both:
newString = oldString.replace(/[\[\]]/g, "");
DEMO
"...there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {... If you want to use any of these characters as a literal in a regex, you need to escape them with a backslash."

[] in a regex is a character class. Since you haven't escaped, them you're saying a "find any of the following characters", and not providing any. Try /[\[\]]/ instead.
edit: #andy is right. forgot to put in a container [].

This is a simple solution :
newString = oldString.split("[]").join("");

had a similair situation. i just used backslash like so.
-replace '\[','' -replace ']',''

Related

Backslash bug in JavaScript

I have a string that involves tricky \\ characters.
Below is the initial code, and what I am literally trying to achieve but it is not working. I have to replace the \" characters but I think that is where the bug is.
var current = csvArray[0][i].Replace("\"", "");
I have tried the variation below but it is still not working.
var current = csvArray[0][i].Replace('\"', '');
It is currently throwing an Uncaught TypeError: csvArray[0][i].Replace is not a function
Is there a way for Javascript to take my string ("\"") literally like in C#? Kindly help me investigate. Thanks!
If the sequence you want to match is a single backslash character followed by a quotation mark, then you need to escape the backslash itself because backslashes have special meaning in string literals. You then need to separately escape the quotation mark with its own backslash:
.replace("\\\"", "")
I believe that would also be true in C#.
Or you can simplify it by using single quotes around the string so that only the backslash needs to be escaped:
.replace('\\"', '')
If the first argument to .replace() is a string, however, it will only replace the first occurrence. To do a global replace you have to use a regular expression with the g flag, noting that backslashes need to be escaped in regular expressions too:
.replace(/\\"/g, '')
I'm not going to setup a demo array to exactly match your code, but here's a simple demo where you can see that a lone backslash or quote in the input string are not replaced, but all backslash-quote combinations are replaced:
var input = 'Some\\ test" \\" text \\" for demo \\"'
var output = input.replace(/\\"/g, '')
console.log(input)
console.log(output)

Escape dot in a regex range

Those two regex act the same way:
var str = "43gf\\..--.65";
console.log(str.replace(/[^\d.-]/g, ""));
console.log(str.replace(/[^\d\.-]/g, ""));
In the first regex I don't escape the dot(.) while in the second regex I do(\.).
What are the differences? Why is the result the same?
The dot operator . does not need to be escaped inside of a character class [].
Because the dot is inside character class (square brackets []).
Take a look at http://www.regular-expressions.info/reference.html, it says (under char class section):
Any character except ^-]\ add that character to the possible matches
for the character class.
If you using JavaScript to test your Regex, try \\. instead of \..
It acts on the same way because JS remove first backslash.
On regular-expressions.info, it is stated:
Remember that the dot is not a metacharacter inside a character class,
so we do not need to escape it with a backslash.
So I guess the escaping of it is unnecessary...

How to use '\' in the regular expression extjs

I am using this regular expression: [a-zA-Z0-9\-.,:+*()=\'&_], but i am getting error like :'unterminated character class' error in this expression':
Demo Code:
Ext.getCmp('field2').addListener({
beforequery: function (e) {
if (e.query && e.query.indexOf('?') != -1) {
var temp = '';
for(var i=0;i<e.query.length;i++){
temp = temp + '['+e.query[i]+ ']';
}
e.cancel = true;
var query = new RegExp(String.format('^{0}',temp.replace(/\?/g, 'a-zA-Z0-9\.,:\+*()=\'&_-\\')));
this.expand();
this.store.clearFilter(true);
this.store.filter(this.displayField, query);
}
}
});
Errors:
1.Please someone tell me whats wrong in this, mainly with backslash.
2.when we enter desired characters in combobox they are being selected automatically..so when we want to enter new character we have to press side arrow or else remaining characters are being deleted...
Thanks once again,
Raj
I think you have to escape some of the items in your character class. Like your backslash, asterisk, plus, parenthesis and period.
Something like this [a-zA-Z0-9\\-\.,:\+\*\(\)=\\'&_]
Adding a backslash to special characters [\^$.|?*+(){} in a regular expression suppresses their special meaning which allows you to use them literally.
http://www.regular-expressions.info/reference.html
In the regex there are 11 characters you need to escape: the opening square bracket [, the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening round bracket ( and the closing round bracket ).
You need to escape some characters in your regular expression. So it would look like:
var regex = /[a-zA-Z0-9\-\.,:\+\*\(\)=\\'&_]/; // Note the backslashes
Parentheses, the plus sign, the asterisk, and the backslash are some of the many characters that have a special meaning in regular expressions. In order to include them literally, you need to escape them with a backslash.

jQuery remove special characters from string and more

I have a string like this:
var str = "I'm a very^ we!rd* Str!ng.";
What I would like to do is removing all special characters from the above string and replace spaces and in case they are being typed, underscores, with a - character.
The above string would look like this after the "transformation":
var str = 'im-a-very-werd-strng';
replace(/[^a-z0-9\s]/gi, '') will filter the string down to just alphanumeric values and replace(/[_\s]/g, '-') will replace underscores and spaces with hyphens:
str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-')
Source for Regex: RegEx for Javascript to allow only alphanumeric
Here is a demo: http://jsfiddle.net/vNfrk/
Assuming by "special" you mean non-word characters, then that is pretty easy.
str = str.replace(/[_\W]+/g, "-")
str.toLowerCase().replace(/[\*\^\'\!]/g, '').split(' ').join('-')
Remove numbers, underscore, white-spaces and special characters from the string sentence.
str.replace(/[0-9`~!##$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi,'');
Demo
this will remove all the special character
str.replace(/[_\W]+/g, "");
this is really helpful and solve my issue. Please run the below code and ensure it works
var str="hello world !#to&you%*()";
console.log(str.replace(/[_\W]+/g, ""));
Since I can't comment on Jasper's answer, I'd like to point out a small bug in his solution:
str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-');
The problem is that first code removes all the hyphens and then tries to replace them :)
You should reverse the replace calls and also add hyphen to second replace regex. Like this:
str.replace(/[_\s]/g, '-').replace(/[^a-z0-9-\s]/gi, '');
Remove/Replace all special chars in Jquery :
If
str = My name is "Ghanshyam" and from "java" background
and want to remove all special chars (") then use this
str=str.replace(/"/g,' ')
result:
My name is Ghanshyam and from java background
Where g means Global
var str = "I'm a very^ we!rd* Str!ng.";
$('body').html(str.replace(/[^a-z0-9\s]/gi, " ").replace(/^\s+|\s+$|\s+(?=\s)/g, "").replace(/[_\s]/g, "-").toLowerCase());
First regex remove special characters with spaces than remove extra spaces from string and the last regex replace space with "-"

regex for content between and including the parenthees

Can someone help me with a regex that will catch the following:
has to be at the end of the string
remove all characters between ( and ) including the parentheses
It's going to me done in javascript.
here's what i have so far -
var title = $(this).find('title').text().replace(/\w+\s+\(.*?\)/, "");
It seems to be catching some chars outside of the parenthees though.
This deals with matching between parens, and only at the of the string: \([^(]*\)\s*$. If the parens might be nested, you need a parser, not a regular expression.
Where's the $? You need a dollar at the end and possibly catch optional whitespace.
var title = $(this).find('title').text().replace(/\s*\([^\)]*?\)\s*$/, "");
If brackets can also be angle brackets, then this can match those too:
var title = $(this).find('title').text().replace(/\s*(\([^\)]*?\)|\<[^\>]*?\>)\s*$/, "");
var title = $(this).find('title').text().replace(/\([^()]*\)\s*$/, "");
should work.
To remove < and > you don't really need regexes, but of course you can do a mystr.replace(/[<>]+/g, "");
This will match a (, any number of characters except parentheses (thereby ensuring that only the last parentheses will match) and a ), and then the end of the string.
Currently, it allows whitespace between the parentheses and the end of the string (and will remove it, too). If that's not desired, remove the \s* bit from the regex.

Categories