I made code with:
element(by.className('charge')).getText()
.then(function(text){
var blabla = "Is this my string?";
expect(text.match(blabla)).toBe(true);
console.log(text);
});
And even is output of my console equal to my blabla variable,
I'm getting result:
Expected [ 'Is this my string' ] to be true.
without any "?" sign.
How is it possible?
The argument for match is:
A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).
So don't pass it a string. Explicitly pass it a regular expression object (since that involves much less pain that converting strings in to regex and having to deal with two levels of syntax to escape through).
Regular expressions treat ? as a special character (in the context of your code it means "The g should appear 0 or 1 time". You need to escape question marks if you want to match them.
var blabla = /Is this my string\?/;
That said, if you want to match the whole string, it would be easier to just make that the test:
var blabla = "Is this my string?";
expect(text).toBe(blabla);
The argument to match is meant to be a regular expression where ? has a special meaning. You probably meant toEqual() instead:
expect(element(by.className('charge')).getText()).toEqual("Is this my string?");
If you want a regular expression match, make a regular expression object and use toMatch():
var blabla = /Is this my string\?/;
expect(element(by.className('charge')).getText()).toMatch(blabla);
Note that in protractor expect() is "patched" to resolve promises implicitly and you don't need to use then().
You probably misundertood what match method does in JS strings:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match
It will basically use the regex to return the groups that match, so, in this case
< ("Is this my string").match("Is this my string?");
> ["Is this my string"]
The answer is correct. What you want to do is simply compare the strings, just do:
< "Is this my string" === "Is this my string?";
> false
Note it has nothing to do with the test engine you are using (that I do not know), but there propably is a better way to do it than
expect(text === blabla).toBe(true);
Something
expect(text, blabla).toBeEqual();
So the error message is pretty ;)
The string argument provided to match() is a regular expression and the ? in this context means "match the previous zero or one times". Which it does in your example :-)
You can explicitly escape the question make by writing \?, in which case the behavior will be as you expect.
Cheers,
Related
I'm trying to prevent an action based on wether a string passes the whiteList Regex in Javascript
const whiteList = /[#A-Za-z0-9.,-]/g // Regex from external source. It will be difficult to modify.
const str= 'ds%d';
console.log(str.replace(whiteList, '').length === 0) // Expected false - WORKS
// How can I make this statement return false ?
console.log(whiteList.test(str)) //Expected false Actual true
Tried using replace command to check if a string passed a validation based on a whitelist. It works but I believe there could be a better way of solving this problem.
You get true from test because there is a character in the string that matches the expression. The expression has no anchors, so it's not that it requires all characters in the string to match, just one. To require all characters to match, you'd need a "start of input" assertion (^) at the beginning, an "end of input" assertion ($) at the end, and either a "zero or more" (*) or "one or more" (+) quantifier on the character class (depending on whether an empty string should pass).
If you're getting the expression from elsewhere, you can add those to it after the fact:
const whiteList = /[#A-Za-z0-9.,-]/g // Regex from external source. It will be difficult to modify.
const str= 'ds%d';
console.log(str.replace(whiteList, '').length === 0);
const improvedList = new RegExp("^" + whiteList.source + "+$");
console.log(improvedList.test(str)); // Now shows false
That does make the assumption that the original regex has the problem described. You might check first, but it would be easy to construct regular expressions that seemed like they needed modifying but didn't.
Alternatively, just use the replace check you have, since it works as well. It's not that much more expensive.
This question already has answers here:
Is there a RegExp.escape function in JavaScript?
(18 answers)
Closed 3 years ago.
I have this Example 1:
myString = 'cdn.google.com/something.png';
console.log(myString.match(myString));
Everything works just fine, but when it comes to Example 2:
myString = 'cdn.google.com/something.png?231564';
console.log(myString.match(myString));
It returns the value of 'null'. I don't know what happened anymore.. I searched for the keywords 'a string does not Match itself' and found nothing. Can somebody help me? Thank you.
The String#match method would treat the argument as a regex(by parsing if not), where . and ? has special meaning.
. matches any character (except for line terminators)
? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed
So . wouldn't cause any problem since . can be used to match any character except line but ? would since it's using to match zero or one-time occurrence of any character.
For eg: .png?23 => matches .png23 or .pn23
From MDN docs :
If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).
It's better to use String#indexOf instead which returns the index in the string if found or returns -1 if not found.
console.log(myString.indexOf(myString) > -1);
match in Javascript compares a String against a RegEx. Luckily in your first example it works.
I guess you are looking for a method like localCompare.
Hope this helps!
match() search the string using a regular expression pattern.
So
var s = "My String";
s.match(/Regex Here/);
will try to match s for given regular expression .
In your example:-
myString = 'cdn.google.com/something.png'; // It will be treated as regex
console.log(myString.match(myString));
myString = 'cdn.google.com/something.png?231564'; // It will be treated as regex , result differ because of ?
console.log(myString.match(myString));
You can escape the argument to match, however if you do that you could just use == to compare the strings. This post contains a regex string escape function:
How to escape regular expression in javascript?
RegExp.quote = function(str) {
return (str+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
};
It can be used like this:
myString = 'cdn.google.com/something.png?231564';
console.log(myString.match(RegExp.quote
(myString)));
If you want to match any number after the question mark, you could do it like this:
myString = 'cdn.google.com/something.png?';
console.log((myString+"18193819").match(RegExp.quote
(myString) + '\\d+'));
I don't want to allow special characters but this regular expression still allows them, what am I doing wrong?
When i type for name : '&é"é&'é"&'&é"'a' It still gives back 'true'
name.match(/[a-zA-Z1-9 ]/))
You need to use RegExp#test with anchors ^ and $.
/^[a-zA-Z1-9 ]+$/.test(name)
String#match return an array if match is found. In your case, a at the end of the string is found and array is returned. And array is truthy in the Javascript. I believe, the array is converted to Boolean, so it returned true.
It returns true because the last character ('a') is ok. Your regex doesn't check whether the complete input matches the regex.
Try this one:
^[a-zA-Z1-9 ]*$
if(!/[^a-zA-Z0-9]/.test(name)) {
// "your validation message"
}
try this
This will work for you:
var nameregex = /^([A-Za-z0-9 ]$)/;
var name = document.getElementById('name').value;
if (!name.match(nameregex)) {
alert('Enter Valid Name!!');
}
Does anyone see why the first three searches in the jsfiddle here - http://jsfiddle.net/tJ9uQ/ return -1?
Thanks
var gotoTarget = "http://register.php?from=";
var off1 = gotoTarget.search('register.php?from=');
console.log ("off1="+off1);
off2 = gotoTarget.search('register.php\?from=');
console.log ("off2="+off2);
off3 = gotoTarget.search('register.phpfrom=');
console.log ("off3="+off3);
off4 = gotoTarget.search('register.php');
console.log ("off4="+off4);
The parameter passed to .search() is a regular expression. If a regular expression is not passed, what is passed is implicitly converted to a regular expression.
Per the MDN Docs:
str.search(regexp)
Parameters
A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).
You need to escape the question mark, as the question mark is a valid regex character.
var off1 = gotoTarget.search('register\\.php\\?from=');
console.log(off1); // returns 7
In your examples above, the first one is not escaped at all, the second is incorrectly escaped and third is missing the ? so no match will be found.
Fiddle
Can someone explain why this does not work? (I am using Chrome Developer Console)
pattern
-> "/Xmp\.MP\.RegionInfo\/MPRI:Regions/"
key
-> "Xmp.MP.RegionInfo/MPRI:Regions[1]"
key.search(pattern)
-> -1
key.search(/Xmp\.MP\.RegionInfo\/MPRI:Regions/)
-> -1
"Xmp.MP.RegionInfo/MPRI:Regions[1]".search(pat)
-> -1
"Xmp.MP.RegionInfo/MPRI:Regions[1]".search(/Xmp\.MP\.RegionInfo\/MPRI:Regions/)
-> 0
It make absolutely no sense to me that the search does not match if i use the variables....
It looks like pattern is a String in your first example, it needs to be a RegExp object:
var pattern = /Xmp\.MP\.RegionInfo\/MPRI:Regions/
var key = "Xmp.MP.RegionInfo/MPRI:Regions[1]"
key.search(pattern); // equals 0
If you want to convert a string to a regex, use the RegExp constructor (but remove the slashes):
var pattern = new RegExp("Xmp\.MP\.RegionInfo\/MPRI:Regions");
http://jsfiddle.net/CpEjA/
In your example pattern appears to be a string. You need it to be a RegExp object.
In first case your pattern is wrapped in quotes, so it is string. In second case it is without quotes -> it is RegExp object.