What does /[\[]/ do in JavaScript? - javascript

I am having trouble googling this. In some code I see
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
/[\[]/ looks to be 1 parameter. What do the symbols do? It looks like it's replacing [] with \[\] but what specifically does /[\[]/ do?

The syntax /…/ is the literal regular expression syntax. And the regular expression [\[] describes a character class ([…]) that’s only character the [ is). So /[\[]/ is a regular expression that describes a single [.
But since the global flag is not set (so only the first match will be replaced), the whole thing could be replaced with this (probably easier to read):
name.replace("[", "\\[").replace("]","\\]")
But if all matches should be replaced, I would probably use this:
name.replace(/([[\]])/g, "\\$1")

It's a regular expression that matches the left square bracket character.
It's a weird way to do it; overall it looks like the code is trying to put backslashes before square brackets in a string, which you could also do like this:
var s2 = s1.replace(/\[/g, '\\[').replace(/]/g, '\\]');
I think.

/[[]/ defined a character range which includes only the ']' character (escaped), you are correct that is replaced [] with [].

The [] is in regex itself used to denote a collection of to-be-matched characters. If you want to represent the actual [ or ] in regex, then you need to escape it by \, hence the [\[] and [\]]. The leading and trailing / are just part of the standard JS syntax to to denote a regex pattern.
After all, it replaces [ by \[ and then replaces ] by \].

Related

Javascript Regex to replace any non-alphanumeric characters, including brackets

I have this regex /[\W_]+/g that I use to remove any non-alphanumeric characters. However it does not remove brackets.
What I need is for it to remove any kind of bracket/paranthesis so that a string like Hello (world) becomes helloworld.
A string like Hello(world) becomes helloworld, but it does not work if there is a space between them.
Is this possible?
You should be able to use this Java / JavaScript compliant regex according to RegexBuddy 4.x:
([\W\s_]+)
And just replace anything it matches with '' or ""
Following the documentation here, something like this:
#set($mystring = "Hello (world)! It's _{now}_ or -- [never]...;")
$mystring.replaceAll("</?([\W\s_]+)/?>", "");
=>
HelloworldItsnowornever

How can I check if a word has parentheses using regular expression

I'm trying to separate the words that has "[]" brackets around them, for example this line
"I hate [running] and [sweating]" how can i use regular expression just to check if a word is wrapped around "running" or "sweating" or any word.
I tried this. but it didn't work.
if(data.word === /[ ]/){}
Here is the expression needed :
/\[([^\[\]]+)\]/
so going by your example we would apply it as the following:
"I hate [running] and [sweating]".match(/\[([^\[\]]+)\]/g)
which will result in the words with the braces , same could be applied on a single word , and we could check whether it match or not to determine if it is surrounded by square brackets
The regular expression you need to test your example string and output all words enclosed by square brackets would be /\[([\w]+)\]/g
The [\w]+ part selects all words comprised of alphanumeric characters. Including \[ and \] explicitly matches the square brackets around those words. The parentheses ( and ) enclose the pattern that describes which parts should be returned.
I can highly recommend regex101.com as a handy playground for trying our regular expressions; it's the first place I went when writing the regular expression above to check for accuracy.
An example of how to implement this can be seen here.

Match last string between special characters

I want to get the last string between special characters. I've done for square bracket as \[(.*)\]$
But, when I use it on something like Blah [Hi]How is this[KoTuWa]. I get the result as [Hi]How is this[KoTuWa].
How do i modify it to get the last stringthat is KotuWa.
Also, I would like to generalise to general special characters, instead of just matching the string between square brackets as above.
Thanks,
Sai
I would do this:
[^[\]]+(?=][^[\]]*$)
Debuggex Demo
To extend this to other types of brackets/special chars, say I also wanna match curly braces { and double quotes ":
[^{}"[\]]+(?=["\]}][^{}"[\]]*$)
Debuggex Demo (I added the multi-line /m only to show multiple examples)
Here is one way to do it:
\[([^\[]*)\]$
You can require that the string between brackets does not contain brackets:
Edit: thanks to funkwurm and jcubic for pointing out an error. Here's the fixed expression:
\[([^[]+)\][^\[]*$
If you need to use other separators than brackets, you should:
replace the \[ and \] with your new separators
replace the negative character classes with your beginning separator.
For example, assuming you need to use the separators <> instead of [], you'd do this:
<([^<]+)>[^\>]*$

Alternation operator inside square brackets does not work

I'm creating a javascript regex to match queries in a search engine string. I am having a problem with alternation. I have the following regex:
.*baidu.com.*[/?].*wd{1}=
I want to be able to match strings that have the string 'word' or 'qw' in addition to 'wd', but everything I try is unsuccessful. I thought I would be able to do something like the following:
.*baidu.com.*[/?].*[wd|word|qw]{1}=
but it does not seem to work.
replace [wd|word|qw] with (wd|word|qw) or (?:wd|word|qw).
[] denotes character sets, () denotes logical groupings.
Your expression:
.*baidu.com.*[/?].*[wd|word|qw]{1}=
does need a few changes, including [wd|word|qw] to (wd|word|qw) and getting rid of the redundant {1}, like so:
.*baidu.com.*[/?].*(wd|word|qw)=
But you also need to understand that the first part of your expression (.*baidu.com.*[/?].*) will match baidu.com hello what spelling/handle????????? or hbaidu-com/ or even something like lkas----jhdf lkja$##!3hdsfbaidugcomlaksjhdf.[($?lakshf, because the dot (.) matches any character except newlines... to match a literal dot, you have to escape it with a backslash (like \.)
There are several approaches you could take to match things in a URL, but we could help you more if you tell us what you are trying to do or accomplish - perhaps regex is not the best solution or (EDIT) only part of the best solution?

How to remove square brackets in string using regex?

['abc','xyz'] – this string I want turn into abc,xyz using regex in javascript. I want to replace both open close square bracket & single quote with empty string ie "".
Use this regular expression to match square brackets or single quotes:
/[\[\]']+/g
Replace with the empty string.
console.log("['abc','xyz']".replace(/[\[\]']+/g,''));
str.replace(/[[\]]/g,'')
here you go
var str = "['abc',['def','ghi'],'jkl']";
//'[\'abc\',[\'def\',\'ghi\'],\'jkl\']'
str.replace(/[\[\]']/g,'' );
//'abc,def,ghi,jkl'
You probably don't even need string substitution for that. If your original string is JSON, try:
js> a="['abc','xyz']"
['abc','xyz']
js> eval(a).join(",")
abc,xyz
Be careful with eval, of course.
Just here to propose an alternative that I find more readable.
/\[|\]/g
JavaScript implementation:
let reg = /\[|\]/g
str.replace(reg,'')
As other people have shown, all you have to do is list the [ and ] characters, but because they are special characters you have to escape them with \.
I personally find the character group definition using [] to be confusing because it uses the same special character you're trying to replace.
Therefore using the | (OR) operator you can more easily distinguish the special characters in the regex from the literal characters being replaced.
This should work for you.
str.replace(/[[\]]/g, "");

Categories