Javascript regex grouping - javascript

I am trying to create a regular expression that would easily replace an input name such as "holes[0][shots][0][unit]" to "holes[0][shots]1[unit]". I'm basically cloning a HTML input and would like to make sure its position is incremented.
I got my regex built and working correctly using this (awesome) tool : http://gskinner.com/RegExr/
Here is my current regex :
(.*\[shots\]\[)([0-9]+)(\].*\])
and I am using a replace such as :
$12$3
this transforms "holes[0][shots][0][unit]" into "holes[0][shots][2][unit]". This is exactly want I want. However, when I try this in javascript (http://jsfiddle.net/PH2Rh/) :
var str = "holes[0][shots][0][units]";
var reg =new RegExp("(.*\[shots\]\[)([0-9]+)(\].*\])", "g");
console.log(str.replace(​reg,'$1'));​​​​​​​​​​​​​​​​​​​​​​​​
I get the following output : holes[0
I don't understand how my first group is supposed to represent "holes[0", since I included the whole [shots][ part in it.
I appreciate any inputs on this. THank you.

In strings, a single \ is not interpreted as a Regex-escaping character. To escape the bracket within string literals, you have to use two backslashes, \\:
var reg = new RegExp("(.*\\[shots\\]\\[)([0-9]+)(\\].*\\])", "g");
A preferable solution is to use RegEx literals:
var reg = /(.*\[shots\]\[)([0-9]+)(\].*\])/g;

Looks like, this works:
var str = "holes[0][shots][0][units]";
var reg = /(.*\[shots\]\[)([0-9]+)(\].*\])/;
console.log(str.replace(​reg,'$1'));​​​​​​​​​​​​​​​​​​​​​​​​

Related

Firefox Extension How to pass string type variable into javascript replace regex parameter?

I've been working on firefox extension for several days now and there is one thing I can't solve.
I generate a list of regex and I wanted to pass that string into replace function in javascript (in the regex parameters). Here is the example of the string:
/(https?:\/\/(www\.)?rapidgator\.net\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))/g
/(https?:\/\/(www\.)?ul\.to\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))/g
/(https?:\/\/(www\.)?uploadable\.ch\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))/g
/(https?:\/\/(www\.)?180upload\.com\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))/g
For a convenient way, lets make it this way. I managed to get the file and get the first line of the string and assign it into a variable:
var rapidgator = "/(https?:\/\/(www\.)?rapidgator\.net\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))/g";
I want the string to be a "replace parameter" like this:
var rep = rep.replace(rapidgator,"<a href='$1'>$1</a>");
But I cant get that work.
I've been trying to use RegExp object and that didn't work to.
var rapidgator = new RegExp("(https?:\/\/(www\.)?rapidgator\.net\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))", "g");
How to make that work? Thank you for your advice :)
If you can get the regex, why not let it remain a regex literal?
var rapidgator = /(https?:\/\/(www\.)?rapidgator\.net\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))/g;
If you want to make it through RegExp constructor, make sure you escape \ with another backslash and you don't need delimiters and the second argument takes the flags.
As in
var rapidgator = new RegExp("(https?:\\/\\/(www\\.)?rapidgator\\.net\\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))","g")
You need to escape the backslash one more time when passing your regex within double quotes.
var rapidgator = new RegExp("(https?://(www\\.)?rapidgator\\.net\\b([-a-zA-Z0-9#:%_\\\\+.~#?&/=]*))", "g");
And also to match a backslash, you need to escape it exactly three times.

jQuery / Javascript replace multiple occurences not working

I'm trying to replace multiple occurrences of a string and nothing seems to be working for me. In my browser or even when testing online. Where am I going wrong?
str = '[{name}] is happy today as data-name="[{name}]" won the match today. [{name}] made 100 runs.';
str = str.replace('/[{name}]/gi','John');
console.log(str);
http://jsfiddle.net/SXTd4/
I got that example from here, and that too wont work.
You must not quote regexes, the correct notation would be:
str = str.replace(/\[{name}\]/gi,'John');
Also, you have to escape the [], because otherwise the content inside is treated as character class.
Updating your fiddle accordingly makes it work.
There are two ways declaring regexes:
// literal notation - the preferred option
var re = /regex here/;
// via constructor
var re = new Regexp('regex here');
You should not put your regex in quotes and you need to escape []
Simply use
str = str.replace(/\[{name}\]/gi,'John');
DEMO
While there are plenty of regex answers here is another way:
str = str.split('[{name}]').join('John');
The characters [ ] { } should be escaped in your regular expression.

How to match a specific regular expression?

I am having a hard time understanding how to match a certain regular expression using javascripts match() function. I have a field in a table stored in the following format:
CH-01-Feb-13-1. I want to be able to grab the date without the dashes, i.e. 01-Feb-13. I was trying to figure out how to combine with ^- or . but not sure how to do it.
So you want the regular expression?
Something like
^\w{2}-(\d{2}-\w{3}-\d{2}).*?$
You can see the explanation here: http://www.regexper.com/ Just copy and paste the expression.
Example with Javascript
var r = /^\w{2}-(\d{2}-\w{3}-\d{2}).*?$/i
var groups = "CH-01-Feb-13-1".match(r);
console.log(groups);
If you are not comfortable with Regex then you can use something like this.
var str = 'CH-01-Feb-13-1';
str = str.replace('CH-','');
str = str.split('-');
str.pop();
console.log(str.join('-'));

Javascript Complex RegEx with variables

I am using this tool to build a regex http://www.gethifi.com/tools/regex
I found that the one below works for me if, for example, I am looking to match $aazz[AB]:
var regex = /[\+\=\-\*\^\\]\$aazz\[AB\]/g;
I have read the other posts on the RegEx constructor in Javascript but cannot manage to make the following work:
var preToken = "[\+\=\-\*\^\\]";
var toFind = "\$aazz\[AB\]";
var stringToReplace = "/" + preToken + toFind + "/";
var regex = new RegExp(stringToReplace, "g");
Here is the jsbin http://jsbin.com/ifeday/3/edit
Thanks
When creating regular expressions from strings, you need to escape your backslashes twice.
\ becomes \\
\\ becomes \\\\
So, you can try (in a character class not everything needs escaping):
var preToken = "[+=\\-*^\\\\]";
var toFind = "azz\\[A\\]";
Also, the string source for your regular expression does not need to be bound by /s, but I see in your jsBin that you've already corrected that.
Update your jsBin with these variable declarations, it should work now.

Javascript RegEx global string search for underscore character(_)

I am horrible with RegEx and I have been using this online tester for some time now and still can not find what I need.
So I have the string "2011_G-20_Cannes_summit". I want to replace all the underscores (_) with spaces.
So I want something like this:
var str = "2011_G-20_Cannes_summit";
str.replace(/_/g," "); or str.replace(/\_/g);
Though neither is working...
What am I missing?
That works fine. The replace method doesn't modify the existing string, it creates a new one. This will do what you want:
var str = "2011_G-20_Cannes_summit";
str = str.replace(/_/g," ");

Categories