What is the difference between RegExp("str","i") and '/'+"str"+'/i' - javascript

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

Related

filter an array based on regex expression [duplicate]

I'm doing a small javascript method, which receive a list of point, and I've to read those points to create a Polygon in a google map.
I receive those point on the form:
(lat, long), (lat, long),(lat, long)
So I've done the following regex:
\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)
I've tested it with RegexPal and the exact data I receive:
(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)
and it works, so why when I've this code in my javascript, I receive null in the result?
var polygons="(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)";
var reg = new RegExp("/\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g");
var result = polygons.match(reg);
I've no javascript error when executing(with debug mode of google chrome). This code is hosted in a javascript function which is in a included JS file. This method is called in the OnLoad method.
I've searched a lot, but I can't find why this isn't working. Thank you very much!
Use a regex literal [MDN]:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
You are making two errors when you use RegExp [MDN]:
The "delimiters" / are should not be part of the expression
If you define an expression as string, you have to escape the backslash, because it is the escape character in strings
Furthermore, modifiers are passed as second argument to the function.
So if you wanted to use RegExp (which you don't have to in this case), the equivalent would be:
var reg = new RegExp("\\(\\s*([0-9.-]+)\\s*,\\s([0-9.-]+)\\s*\\)", "g");
(and I think now you see why regex literals are more convenient)
I always find it helpful to copy and past a RegExp expression in the console and see its output. Taking your original expression, we get:
/(s*([0-9.-]+)s*,s([0-9.-]+)s*)/g
which means that the expressions tries to match /, s and g literally and the parens () are still treated as special characters.
Update: .match() returns an array:
["(25.774252, -80.190262)", "(18.466465, -66.118292)", ... ]
which does not seem to be very useful.
You have to use .exec() [MDN] to extract the numbers:
["(25.774252, -80.190262)", "25.774252", "-80.190262"]
This has to be called repeatedly until the whole strings was processed.
Example:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
var result, points = [];
while((result = reg.exec(polygons)) !== null) {
points.push([+result[1], +result[2]]);
}
This creates an array of arrays and the unary plus (+) will convert the strings into numbers:
[
[25.774252, -80.190262],
[18.466465, -66.118292],
...
]
Of course if you want the values as strings and not as numbers, you can just omit the +.

Replace all occurences of \n\r from a string [duplicate]

I'm doing a small javascript method, which receive a list of point, and I've to read those points to create a Polygon in a google map.
I receive those point on the form:
(lat, long), (lat, long),(lat, long)
So I've done the following regex:
\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)
I've tested it with RegexPal and the exact data I receive:
(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)
and it works, so why when I've this code in my javascript, I receive null in the result?
var polygons="(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)";
var reg = new RegExp("/\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g");
var result = polygons.match(reg);
I've no javascript error when executing(with debug mode of google chrome). This code is hosted in a javascript function which is in a included JS file. This method is called in the OnLoad method.
I've searched a lot, but I can't find why this isn't working. Thank you very much!
Use a regex literal [MDN]:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
You are making two errors when you use RegExp [MDN]:
The "delimiters" / are should not be part of the expression
If you define an expression as string, you have to escape the backslash, because it is the escape character in strings
Furthermore, modifiers are passed as second argument to the function.
So if you wanted to use RegExp (which you don't have to in this case), the equivalent would be:
var reg = new RegExp("\\(\\s*([0-9.-]+)\\s*,\\s([0-9.-]+)\\s*\\)", "g");
(and I think now you see why regex literals are more convenient)
I always find it helpful to copy and past a RegExp expression in the console and see its output. Taking your original expression, we get:
/(s*([0-9.-]+)s*,s([0-9.-]+)s*)/g
which means that the expressions tries to match /, s and g literally and the parens () are still treated as special characters.
Update: .match() returns an array:
["(25.774252, -80.190262)", "(18.466465, -66.118292)", ... ]
which does not seem to be very useful.
You have to use .exec() [MDN] to extract the numbers:
["(25.774252, -80.190262)", "25.774252", "-80.190262"]
This has to be called repeatedly until the whole strings was processed.
Example:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
var result, points = [];
while((result = reg.exec(polygons)) !== null) {
points.push([+result[1], +result[2]]);
}
This creates an array of arrays and the unary plus (+) will convert the strings into numbers:
[
[25.774252, -80.190262],
[18.466465, -66.118292],
...
]
Of course if you want the values as strings and not as numbers, you can just omit the +.

Using regex to split double hyphen but not single hyphen

I have an html element id that looks like this:
dp__1-2--1-3
I'm trying to use the JavaScript split() function to lop off and return the final '1-3'
My regex skills are poor but a bit of searching around got me to this point:
var myId = "dp__1-2--1-3";
var myIdPostFix = myId.split(/[\-\-]+/).pop();
Unfortunately that returns me only the '3'.
So my question is how do I split double hyphens but NOT single hyphens?
It's the brackets in the regular expression that keeps it from working. A set will match one of any of the characers in it, so [\-\-] is the same as [\-], i.e. matching a single hyphen.
Just remove the brackets:
var myIdPostFix = myId.split(/--/).pop();
or just use the string '--' instead of a regular expression:
var myIdPostFix = myId.split('--').pop();
split accepts a regular expression or a string as the first argument.
You were very close. You can achieve what you want with:
var myIdPostFix = myId.split("--").pop();

Why doesn't a regex pattern qualify as a javascript data type?

var rclass = /[\n\t\r]/g;
In the above, there are no "", or '' around it, so it cannot be a string, is this not its own data type? Why then does it not qualify?
Also, why do we not put "", '' around it and just represent it as a string?
In JavaScript you can create most things in two ways.
Either by calling its constructor function:
var myConstructedString = new String( "foo" );
var myConstructedRegExp = new RegExp("[\n\t\r]", "g");
Or using literals:
var myLiteralString = "bar";
var myLiteralRegExp = /[\n\t\r]/g;
Regular Expressions is no exception. Date is one type (Date actually not being a type but a sub type of the Object type) that has no literal notation.
So to answer one of your questions, "is this not its own data type?". No it´s not, RegExp is of type Object, just like Date and Math. There are only six types in JavaScript
A good read is this article at MDN.
when you have:
var myRegex = /myRegex/;
typeof myRegex returns "object" and not "string".
This means that /myRegex/ is actualy not a string but a real object with its own methods (I can see on it an "exec" function for example, or "ignoreCase"...).
I also found the Object RegExp: new RegExp("myRegex") returns .... /myregex/ :-)
It turns out that the way of creating a regex with /myRegex/ syntax is a syntax convention equivalent to new RegExp("myRegex").
Because that is how you define a regular expression in JS. A regular expression is delimited by the / characters. Remember, that a regular expression is not a string, it is something in its own right. This is a nice article on the matter.

RegEx test for string ending?

I'm horrible at RegEx and I need a regex to test if a certain string ends a certain way. For example, if the RegEx tests for ending with foo, "somestringfoo" -> True and "someotherFoostring" -> False. It needs to be case sensitive and work with alphanumeric and underscore. Here is what I've got, but I can't get it to work:
var test = RegExp.test('/foo$/');
You would do it this way:
/foo$/.test("somestringfoo")
test is a method of the regexp object, so it would be /foo$/.test(someString) or new Regexp("foo$").test(someString).
However, testing a string for ending with a certain substring does not need regular expressions, see endsWith in JavaScript.
this should do the work:
function isFoo(string){
var pattern = /foo$/;
return pattern.test(string);
}

Categories

Resources