Why am I not able to grab the subpattern? The console displays undefined when I am expecting hello to be output. If I change matches[1] to matches[0] I get {{hello}}. So, Why can I not access the subpattern?
var str = "{{hello}}";
var matches = str.match(/{{(.+)}}/ig);
console.log(matches[1]);
Try:
str.match(/{{(.+)}}/i);
instead.
It seems like you're looking for the behavior of RegExp.exec. MDN states this:
If the regular expression does not include the g flag, returns the same result as regexp.exec(string). ...
If the regular expression includes the g flag, the method returns an Array containing all matches.
Since you had the g flag, the RegExp was trying to find all global matches (basically ignoring your groupings), returning ['{{hello}}'].
If you remove the the g flag (or alternatively use /{{(.+)}}/i.exec(str), you can get your groupings returned.
Related
I have a piece of code as follows:
var str = "foo xxx eee dsds";
var regex = /(foo)/;
console.log(str.match(regex));
I expected output is:
foo
But the actual output is:
foo, foo
If i declare:
var regex = /(foo)/g;
The output only is foo
Can anyone help me? Thank for your help.
The second value in the array is the captured value, in absence of global modifiers match results contains the captured values. If you are removed the capturing group the result will only contains the match.
var str = "foo xxx eee dsds";
console.log(str.match(/(foo)/));
console.log(str.match(/(foo)/g));
console.log(str.match(/foo/));
Check MDN documentation :
If the regular expression does not include the g flag, returns the same result as RegExp.exec(). The returned Array has an extra input property, which contains the original string that was parsed. In addition, it has an index property, which represents the zero-based index of the match in the string.
If the regular expression includes the g flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns null.
Your output is a return value of the match method which is an array. To get the desired output, use either str.match(regex)[0] (the whole matched string) or str.match(regex)[1] (the captured substring matching (foo) which is the same in your case). But it's better to save the match array first and check if it is null or not (if the string doesn't match, it is null and null[0] will cause an error):
var match = str.match(regex);
if(match)
console.log(match[0]);
else
// do whatever you want when there's no match
I tried to do a case insensitive regular expression search by creating a string like so:
var regEx = '/'+myStr+'/i';
but when I use it in a search, it always returns -1.
If I use:
var regEx = RegExp(myStr,'i');
it works like a champ.
I'd just like to understand why?
You first example will create a string, not a regular expression object.
var myStr = 'test';
var regEx = '/'+myStr+'/i';
console.log(typeof regEx);//string
Using RegExp will create a regular expression object.
var myStr = 'test';
var regEx = RegExp(myStr,'i');
console.log(typeof regEx);//object
Thus when you try to use the search method, you are searching with a string on slashes on both sides, thus getting -1.
var s = 'just a test string';
console.log(s.search('/test/'));//-1
console.log(s.search(/test/));//7
Of course, the string search method can work with a string, in which case it will search for that specific substring, which in your case does not exist, so it returns the -1 index. In your example slashes were being added to the string, rather than producing the intended regular expression.
In JavaScript, there are two ways of creating a regular expression object (short of using code evaluation), a regular expression literal, and one created by the RegExp constructor.
A regular expression literal has to be defined at compile time, and cannot be constructed from string concatenation.
/test/i
To dynamically create a regular expression at runtime, you have to use the RegExp constructor.
RegExp('test', 'i');
This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 7 years ago.
Why is this code returning first true, then false
var pattern = new RegExp("mstea", 'gi'), name = "Amanda Olmstead";
console.log('1', pattern.test(name));
console.log('1', pattern.test(name));
Demo: Fiddle
g is for repeating searches. It changes the regular expression object into an iterator. If you want to use the test function to check your string is valid according to your pattern, remove this modifier :
var pattern = new RegExp("mstea", 'i'), name = "Amanda Olmstead";
The test function, contrary to replace or match doesn't consume the whole iteration, which lets it in a "bad" state. You should probably never use this modifier when using the test function.
You don't want to use gi in combination with pattern.test. The g flag means that it keeps track of where you are running so it can be reused. So instead, you should use:
var pattern = new RegExp("mstea", 'i'), name = "Amanda Olmstead";
console.log('1', pattern.test(name));
console.log('1', pattern.test(name));
Also, you can use /.../[flags] syntax for regex, like so:
var pattern = /mstea/i;
Because you set the g modifier.
Remove it for your case.
var pattern = new RegExp("mstea", 'i'), name = "Amanda Olmstead";
It isn't a bug.
The g causes it to carry out the next attempted match for the substring, after the first match. And that is why it returns false in every even attempt.
First attempt:
It is testing "Amanda Olmstead"
Second attempt:
It is testing "d" //match found in previous attempt (performs substring there)
Third attempt:
It is testing "Amanda Olmstead" again //no match found in previous attempt
... so on
MDN page for Regexp.exec states:
If your regular expression uses the "g" flag, you can use the exec
method multiple times to find successive matches in the same string.
When you do so, the search starts at the substring of str specified by
the regular expression's lastIndex property
MDN page for test states:
As with exec (or in combination with it), test called multiple times
on the same global regular expression instance will advance past the
previous match.
re = //?(\w+)/(\w+)/
s = '/projects/new'
s.match(re)
I have this regular expression which I will use to sieve out the branch name, e.g., projects, and the 'tip' name, e.g., new
I read that one can have access to the grouped results with $1, $2, and so on, but I can't seem to get it to work, at least in Firebug console
When I run the above code, then run
RegExp.$1
it shows
""
Same goes on for $2.
any ideas?
Thanks!
Without the g flag, str.match(regexp) returns the same as regexp.exec(str). And that is:
The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured. If the match fails, the exec method returns null.
So you can do this:
var match = s.match(re);
match[1]
match gives you an array of the matched expressions:
> s.match(re)[1]
"projects"
> s.match(re)[2]
"new"
I you are accessing the array of matches the wrong way do something like:
re = /\/?(\w+)\/(\w+)/
s = '/projects/new'
var j = s.match(re)
alert(j[1]);
alert(j[2]);
I am doing it wrong. I know.
I want to assign the matched text that is the result of a regex to a string var.
basically the regex is supposed to pull out anything in between two colons
so blah:xx:blahdeeblah
would result in xx
var matchedString= $(current).match('[^.:]+):(.*?):([^.:]+');
alert(matchedString);
I am looking to get this to put the xx in my matchedString variable.
I checked the jquery docs and they say that match should return an array. (string char array?)
When I run this nothing happens, No errors in the console but I tested the regex and it works outside of js. I am starting to think I am just doing the regex wrong or I am completely not getting how the match function works altogether
I checked the jquery docs and they say that match should return an array.
No such method exists for jQuery. match is a standard javascript method of a string. So using your example, this might be
var str = "blah:xx:blahdeeblah";
var matchedString = str.match(/([^.:]+):(.*?):([^.:]+)/);
alert(matchedString[2]);
// -> "xx"
However, you really don't need a regular expression for this. You can use another string method, split() to divide the string into an array of strings using a separator:
var str = "blah:xx:blahdeeblah";
var matchedString = str.split(":"); // split on the : character
alert(matchedString[1]);
// -> "xx"
String.match
String.split