Videos
Use regex.test() if all you want is a boolean result:
console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false
console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true
console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true
...and you could remove the () from your regexp since you've no need for a capture.
Use test() method :
var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
console.log("Valid");
} else {
console.log("Invalid");
}
You can use a string as a regular expression using the RegExp Object:
var myPattern = new RegExp('.'+myWord,'g');
Fiddle Example
Doing a single match in your case, is simply changed the second parameter in RegExp from g to m (which means to make one match per line for multi lines, but in this case a strings is simply all one line). For finding the word "wood" from "ood","od","d", or other cases. You can do this:
var myPattern = new RegExp("\\b\\w+"+myWord+"\\b",'m');
Note I have a solution in the comments below, but this one is better.
The items \\b ... \\b mean word boundaries. Basically ensuring that it matches a single word. Then the \\w means any valid "word character". So overall the regexp means (using myWord = "od"):
|word boundary| + (1 or more word characters) + "od" + |word boundary|
This will ensure that it matches any words in the string than end with the characters "od". Or in a more general case you can do:
var myPattern = new RegExp("\\b\\w*"+myWord+"\\w*\\b",'m');
Create a Regexp object like
new RegExp('.ood','g');
like in
var searchstring='ood' // this is the one you get in a variable ...
var myString = "How much wood could a wood chuck chuck";
var myPattern=new RegExp('.'+searchstring,'gi');
var myResult = myString.match(myPattern);
Use the regex constructor, like:
function myFunction() {
var str = "The rain in SPAIN stays mainly in the plain",
test = "ain",
re = new RegExp(test, 'gi'),
res = str.match(re);
console.log(res);
}
You need to use RegExp constructor if you want to pass a value of variable as regex.
var test = "ain";
var re = new RegExp(test, "gi");
If your variable contains special chars, it's better to escape those.
var re = new RegExp(test.replace(/(\W)/g, "\\$1"), "gi");
Global Variable Scope
It is because you are using name as your variable. This is a global browser window variable that is inherently a string and cannot be stored as an Array
Even if you redeclare it with var name =, you are still in the global scope. And thus name (aka window.name) simply retains the last value you assign to it.
You can test this with the following on an empty page without defining any variables at all:
console.log(name===window.name) // Returns true
console.log(name,window.name) // Returns 'Safari Safari' for my browser
Change name to something else
If you change your name variable to simply have a different name, like my_name, it stores the result of .match() as an Array.
var my_name = str.match(/[^\/]+/i);
var version = str.match(/[0-9|\.]+/i);
console.log(typeof my_name, my_name instanceof Array) // Returns object, true
Change Scope by wrapping in a function
This is your exact code wrapped inside a function and returns the correct variable types:
function getBrowserStuff(){
var userAgent = navigator.userAgent;
var splitted = userAgent.match(/[(][^)]+[)]|\w+\/\S+/ig);
for (var i = 0; i < splitted.length; i++ ) {
var str = splitted[i];
if (str[0] == '(') {
} else {
var name = str.match(/[^\/]+/i);
var version = str.match(/[0-9|\.]+/i);
console.log('Name','Typeof '+(typeof name), 'IsArray '+(name instanceof Array),name)
console.log('Version','Typeof '+(typeof version),'IsArray '+(version instanceof Array),version)
}
}
return 'whatever'
}
getBrowserStuff()
Changing the variable name to my_name OR wrapping code like the above function returns this:
Name Typeof object IsArray true ["Mozilla"]
Version Typeof object IsArray true ["5.0"]
Name Typeof object IsArray true ["AppleWebKit"]
Version Typeof object IsArray true ["600.3.18"]
Name Typeof object IsArray true ["Version"]
Version Typeof object IsArray true ["8.0.3"]
Name Typeof object IsArray true ["Safari"]
Version Typeof object IsArray true ["600.3.18"]
Where before it returned this:
Name Typeof string IsArray false Mozilla
Version Typeof object IsArray true ["5.0"]
Name Typeof string IsArray false AppleWebKit
Version Typeof object IsArray true ["600.3.18"]
Name Typeof string IsArray false Version
Version Typeof object IsArray true ["8.0.3"]
Name Typeof string IsArray false Safari
Version Typeof object IsArray true ["600.3.18"]
This is not possible, or is a bug of your implementation.
According to the ECMAScript 5.1 specification, match behaves like this:
15.5.4.10 String.prototype.match (regexp)
When the
matchmethod is called with argument regexp, the following steps are taken:
- Call CheckObjectCoercible passing the this value as its argument.
- Let S be the result of calling ToString, giving it the this value as its argument.
- If Type(regexp) is Object and the value of the [[Class]] internal property of regexp is "
RegExp", then let rx be regexp;- Else, let rx be a new RegExp object created as if by the expression
new RegExp(regexp)whereRegExpis the standard built-in constructor with that name.- Let global be the result of calling the [[Get]] internal method of rx with argument "
global".- Let exec be the standard built-in function
RegExp.prototype.exec(see 15.10.6.2)- If global is not true, then
- Return the result of calling the [[Call]] internal method of exec with rx as the this value and argument list containing S.
- Else, global is true
- Call the [[Put]] internal method of rx with arguments "
lastIndex" and 0.- Let A be a new array created as if by the expression
new Array()whereArrayis the standard built-in constructor with that name.- Let previousLastIndex be 0.
- Let n be 0.
- Let lastMatch be true.
- Repeat, while lastMatch is true
- Let result be the result of calling the [[Call]] internal method of exec with rx as the this value and argument list containing S.
- If result is null, then set lastMatch to false.
- Else, result is not null
- Let thisIndex be the result of calling the [[Get]] internal method of rx with argument "
lastIndex".- If thisIndex = previousLastIndex then
- Call the [[Put]] internal method of rx with arguments "
lastIndex" and thisIndex+1.- Set previousLastIndex to thisIndex+1.
- Else, set previousLastIndex to thisIndex.
- Let matchStr be the result of calling the [[Get]] internal method of result with argument "
0".- Call the [[DefineOwnProperty]] internal method of A with arguments ToString(n), the Property Descriptor {[[Value]]: matchStr, [[Writable]]: true, [[Enumerable]]: true, [[configurable]]: true}, and false.
- Increment n.
- If n = 0, then return null.
- Return A.
Therefore, for your global regex, the only possible returned values are null or A, which is an array.
For the non global ones, the result of calling RegExp.prototype.exec is returned. But it also returns an array or null:
Performs a regular expression match of string against the regular expression and returns an Array object containing the results of the match, or null if string did not match.