How can I put [] (square brackets) in RegExp javascript? - javascript

I'm trying this:
str = "bla [bla]";
str = str.replace(/\\[\\]/g,"");
console.log(str);
And the replace doesn't work, what am I doing wrong?
UPDATE: I'm trying to remove any square brackets in the string,
what's weird is that if I do
replace(/\[/g, '')
replace(/\]/g, '')
it works, but
replace(/\[\]/g, ''); doesn't.

It should be:
str = str.replace(/\[.*?\]/g,"");
You don't need double backslashes (\) because it's not a string but a regex statement, if you build the regex from a string you do need the double backslashes ;).
It was also literally interpreting the 1 (which wasn't matching). Using .* says any value between the square brackets.
The new RegExp string build version would be:
str=str.replace(new RegExp("\\[.*?\\]","g"),"");
UPDATE: To remove square brackets only:
str = str.replace(/\[(.*?)\]/g,"$1");
Your above code isn't working, because it's trying to match "[]" (sequentially without anything allowed between). We can get around this by non-greedy group-matching ((.*?)) what's between the square brackets, and using a backreference ($1) for the replacement.
UPDATE 2: To remove multiple square brackets
str = str.replace(/\[+(.*?)\]+/g,"$1");
// bla [bla] [[blaa]] -> bla bla blaa
// bla [bla] [[[blaa] -> bla bla blaa
Note this doesn't match open/close quantities, simply removes all sequential opens and closes. Also if the sequential brackets have separators (spaces etc) it won't match.

You have to escape the bracket, like \[ and \]. Check out http://regexpal.com/. It's pretty useful :)
To replace all brackets in a string, this should do the job:
str.replace(/\[|\]/g,'');
I hope this helps.
Hristo

Here's a trivial example but worked for me. You have to escape each sq bracket, then enclose those brackets within a bracket expression to capture all instances.
const stringWithBrackets = '[]]][[]]testing][[]][';
const stringWithReplacedBrackets = stringWithBrackets.replace(/[\[\]]/g, '');
console.log(stringWithReplacedBrackets);

Two backslashes produces a single backslash, so you're searching for "a backslash, followed by a character class consisting of a 1 or a right bracket, and then you're missing an closing bracket.
Try
str.replace(/\[1\]/g, '');

What exactly are you trying to match?
If you don't escape the brackets, they are considered character classes. This:
/[1\\]/
Matches either a 1 or a backslash. You may want to escape them with one backslash only:
/\[1\]/
But this won't match either, as you don't have a [1] in your string.

I stumbled on this question while dealing with square bracket escaping within a character class that was designed for use with password validation requiring the presence of special characters.
Note the double escaping:
var regex = new RegExp('[\\]]');
As #rudu mentions, this expression is within a string so it must be double escaped. Note that the quoting type (single/double) is not relevant here.
Here is an example of using square brackets in a character class that tests for all the special characters found on my keyboard:
var regex = new RegExp('[-,_,\',",;,:,!,#,#,$,%,^,&,*,(,),[,\\],\?,{,},|,+,=,<,>,~,`,\\\\,\,,\/,.]', 'g')

How about the following?
str = "bla [bla]";
str.replace(/[[\\]]/g,'');
You create a character set with just the two characters you are interested in and do a global replace.

Nobody quite made it simple and correct:
str.replace(/[[\]]/g, '');
Note the use of a character class, with no escape for the open bracket, and a single backslash escape for the close bracket.

Related

why does this js RegExp test return true? [duplicate]

The regex allows chars that are: alphanumeric, space, '-', '_', '&', '()' and '/'
this is the expression
[\s\/\)\(\w&-]
I have tested this in various online testers and know it works, I just can't get it to work correctly in code. I get sysntax errors with anything I try.. any suggestions?
var programProductRegex = new RegExp([\s\/\)\(\w&-]);
You can use the regular expression syntax:
var programProductRegex = /[\s\/\)\(\w&-]/;
You use forward slashes to delimit the regex pattern.
If you use the RegExp object constructor you need to pass in a string. Because backslashes are special escape characters inside JavaScript strings and they're also escape characters in regular expressions, you need to use two backslashes to do a regex escape inside a string. The equivalent code using a string would then be:
var programProductRegex = new RegExp("[\\s\\/\\)\\(\\w&-]");
All the backslashes that were in the original regular expression need to be escaped in the string to be correctly interpreted as backslashes.
Of course the first option is better. The constructor is helpful when you obtain a string from somewhere and want to make a regular expression out of it.
var programProductRegex = new RegExp(userInput);
If you are using a String and want to escape characters like (, you need to write \\( (meaning writing backslash, then the opening parenthesis => escaping it).
If you are using the RegExp object, you only need one backslash for each character (like \()
Enclose your regex with delimiters:
var programProductRegex = /[\s\/)(\w&-]/;

Why do I have to add double backslash on javascript regex?

When I use a tool like regexpal.com it let's me use regex as I am used to. So for example I want to check a text if there is a match for a word that is at least 3 letters long and ends with a white space so it will match 'now ', 'noww ' and so on.
On regexpal.com this regex works \w{3,}\s this matches both the words above.
But on javascript I have to add double backslashes before w and s. Like this:
var regexp = new RegExp('\\w{3,}\\s','i');
or else it does not work. I looked around for answers and searched for double backslash javascript regex but all I got was completely different topics about how to escape backslash and so on. Does someone have an explanation for this?
You could write the regex without double backslash but you need to put the regex inside forward slashshes as delimiter.
/^\w{3,}\s$/.test('foo ')
Anchors ^ (matches the start of the line boundary), $ (matches the end of a line) helps to do an exact string match. You don't need an i modifier since \w matches both upper and lower case letters.
Why? Because in a string, "\" quotes the following character so "\w" is seen as "w". It essentially says "treat the next character literally and don't interpret it".
To avoid that, the "\" must be quoted too, so "\\w" is seen by the regular expression parser as "\w".

Replace text containing number in js

I would like to use .replace() function in JS to replace all occurencies of string "{5}".
I had no problems with letters in brackets but numbers just dont work if I call:
mystring.replace(/{\5}/g,'replaced')
nothing happens. Please can you help me with right syntax?
It looks like you have a problem with escaping. I'm pretty sure \5 is a backreference. You should instead be escaping the curly braces and not the number.
'Something {5} another thing'.replace(/\{5\}/g, 'replaced');
// -> Something replaced another thing
Additional Note: Just in case you're looking for a generalized string formatting solution, check out this SO question with some truly awesome answers.
Is there a special reason you are preceding the number with a backslash? If your intention is to match against the string "{5}", "{" and "}" are the special characters that should be escaped, not the character "5" itself!
According to MDN:
A backslash that precedes a non-special character indicates that the next character is
special and is not to be interpreted literally. For example, a 'b' without a preceding '\' generally matches lowercase 'b's wherever they occur. But a '\b' by itself doesn't match any character; it forms the special word boundary character.
The following code would work:
var str = "foo{5}bar{5}";
var newStr = str.replace(/\{5\}/g, "_test_");
console.log(newStr); // logs "foo_test_bar_test_"
Try this:
mystring.replace(/\{5\}/g,'replaced');
You need to escape the curly brackets\{ and \}.
DEMO
http://jsfiddle.net/tuga/Gnsq3/

javascript regex replace spaces between brackets

How can I use JS regex to replace all occurences of a space with the word SPACE, if between brackets?
So, what I want is this:
myString = "a scentence (another scentence between brackets)"
myReplacedString = myString.replace(/*some regex*/)
//myReplacedString is now "a scentence (anotherSPACEscentenceSPACEbetweenSPACEbrackets)"
EDIT:
what I've tried is this (I'm quite new to regular expressions)
myReplacedString = myString.replace(/\(\s\)/, "SPACE");
You could perhaps use the regex:
/\s(?![^)]*\()/g
This will match any space without an opening bracket ahead of it, with no closing bracket in between the space and the opening bracket.
Here's a demo.
EDIT: I hadn't considered cases where the sentences don't end with brackets. The regexp of #thg435 covers it, however:
/\s(?![^)]*(\(|$))/g
I'm not sure about one regex, but you can use two. One to get the string inside the (), then another to replace ' ' with 'SPACE'.
myReplacedString = myString.replace(/(\(.*?\))/g, function(match){
return match.replace(/ /g, 'SPACE');
});

Brackets in Regular Expression

I'd like to compare 2 strings with each other, but I got a little problem with the Brackets.
The String I want to seek looks like this:
CAPPL:LOCAL.L_hk[1].vorlauftemp_soll
Quoting those to bracket is seemingly useless.
I tried it with this code
var regex = new RegExp("CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll","gi");
var value = "CAPPL:LOCAL.L_hk[1].vorlauftemp_soll";
regex.test(value);
Somebody who can help me??
It is useless because you're using string. You need to escape the backslashes as well:
var regex = new RegExp("CAPPL:LOCAL.L_hk\\[1\\].vorlauftemp_soll","gi");
Or use a regex literal:
var regex = /CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll/gi
Unknown escape characters are ignored in JavaScript, so "\[" results in the same string as "[".
In value, you have (1) instead of [1]. So if you expect the regular expression to match and it doesn't, it because of that.
Another problem is that you're using "" in your expression. In order to write regular expression in JavaScript, use /.../g instead of "...".
You may also want to escape the dot in your expression. . means "any character that is not a line break". You, on the other hand, wants the dot to be matched literally: \..
You are generating a regular expression (in which [ is a special character that can be escaped with \) using a string (in which \ is a special character).
var regex = /CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll/gi;

Categories

Resources