Javascript Complex RegEx with variables - javascript

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.

Related

JavaScript - strip everything before and including a character

I am relatively new to RegEx and am trying to achieve something which I think may be quite simple for someone more experienced than I.
I would like to construct a snippet in JavaScript which will take an input and strip anything before and including a specific character - in this case, an underscore.
Thus 0_test, 1_anotherTest, 2_someOtherTest would become test, anotherTest and someOtherTest, respectively.
Thanks in advance!
You can use the following regex (which can only be great if your special character is not known, see Alex's solution for just _):
^[^_]*_
Explanation:
^ - Beginning of a string
[^_]* - Any number of characters other than _
_ - Underscore
And replace with empty string.
var re = /^[^_]*_/;
var str = '1_anotherTest';
var subst = '';
document.getElementById("res").innerHTML = result = str.replace(re, subst);
<div id="res"/>
If you have to match before a digit, and you do not know which digit it can be, then the regex way is better (with the /^[^0-9]*[0-9]/ or /^\D*\d/ regex).
Simply read from its position to the end:
var str = "2_someOtherTest";
var res = str.substr(str.indexOf('_') + 1);

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.

RegEx match not working

So what I want to match is anything that ends with ".ProjectName" so I wrote a small test case. I purposely created the pattern using RegExp because in the real case scenario I will be using a variable as part of the reg ex pattern. I'm not sure if my pattern is not correct (90% sure it correct), or if I am misusing the match function (70% sure I am suing it right). The blow code returns me something when the second case notMatchName should not return me anything
var inputName = "ProjectName";
var matchName = "userInput_Heading.Heading.ProjectName";
var notMatchName = "userInput_Heading.Heading.Date";
var reg = new RegExp(".*[." + inputName + "]");
console.log(reg);
console.log(matchName.match(reg));
console.log(matchName.match(reg)[0]);
console.log(notMatchName.match(reg));
console.log(notMatchName.match(reg)[0]);
Here is the JsFiddle to help.
Use
var reg = new RegExp(".*\." + inputName);
The square brackets mean: one character, which is one of those within the brackets. But you want several characzters, first a dot, then the first character of inputName, etc.
your regular expression should be .*\.projectName
if you rewrite your statement it will be
var reg = new RegExp(".*\." + inputName)

Javascript regex grouping

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'));​​​​​​​​​​​​​​​​​​​​​​​​

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