test string against multiple regexes in javascript - javascript

I want to test a given string against 20 or so regular expressions. What's a clean way to do this in Javascript? I'm more concerned about clean code and readability than efficiency (but I don't want it to be super slow either).
Right now I have:
if (href.indexOf('apple.com') > -1 ||
href.indexOf('google.com') > -1 ||
href.indexOf('yahoo.com') > -1 ||
href.indexOf('facebook.com') > -1) {
performDarkMagic()
}
But it's going to start looking kind of messy as that list grows.
Maybe I could just create an array of regular expressions and execute something like _.any() and apply regex.test on each?
Edit: the strings/regexes to match may become more complicated, I just used simple URLs to make the example readable.

Use the test function for regular expressions.
More information on regular expressions here.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp
var re = /((google)|(facebook)|(yahoo)|(apple))\.com/;
re.test( str ); // returns true or false;
Test cases.
Live Demo Here:
http://jsfiddle.net/rkzXP/1/
var func = function( str ){
var re = /((google)|(facebook)|(yahoo)|(apple))\.com/;
return re.test( str );
};
test("test for valid values", function() {
equal( func("google.com"), true);
equal( func("facebook.com"), true);
equal( func("apple.com"), true);
});
test("test for invalid values", function() {
equal( func("googl.com"), false);
equal( func("faceook.com"), false);
equal( func("apple"), false);
});
So you can rewrite your code as the following.
var re = /((google)|(facebook)|(yahoo)|(apple))\.com/;
if( re.test(str) ){
performDarkMagic()
}

var patterns = ['apple.com', 'google.com', 'yahoo.com', 'facebook.com', ...]
var callFunc = false;
patterns.forEach(function(item){
if(href.indexOf(item) > -1){
callFunc = true;
break;
}
});
if(callFunc) {
performDarkMagic();
}

Yes, building an array and using .any() or .some() is just fine, especially when there will be more than 4 values:
if (["apple","google","yahoo","facebook"].some(host => href.includes(`${host}.com`)) {
performLightMagic();
}
Yet I can't see regexes there, there are just strings; so you could simplify using regex.test() to:
if (/apple\.com|google\.com|yahoo\.com|facebook\.com/.test(href)) { performLightMagic(); }
or even
if (/(apple|google|yahoo|facebook)\.com/.test(href)) { performLightMagic(); }

You could put each one in array then looping over each.

How I would do it: factor it out into a function. Put each regex in an array, loop over them and return true the first time indexOf > -1. If you reach the end of the loop return false.

Loop through a regex array and then do:
result=result AND (result_of_regex);
next;
after the loop return result

Related

Extract sub string from last in a string JS [duplicate]

This question already has answers here:
endsWith in JavaScript
(30 answers)
Closed 9 years ago.
I need to write JS function which returns true if string contains - depreciated in its last otherwise false.
For example:
var somestring = "string value - depreciated";
function should return true in above example.
function isDepreciated(var S)
{
//Need to check for substring in last
//return true or false
}
One possible solution is to use search function but that means that if - depreciated comes within string then it will also return true. I really need to find weather substring is in last or not.
Please help.
Add the below code in your JS
function isDepreciated(string){
return /(-depreciated)$/.test(string);
}
You'll want to use the Javascript string method .substr() combined with the .length property.
function isDepreciated(var id)
{
var id = "string value - depreciated";
var lastdepreciated = id.substr(id.length - 13); // => "- depreciated"
//return true or false check for true or flase
}
This gets the characters starting at id.length - 13 and, since the second argument for .substr() is omitted, continues to the end of the string.
function isDepreciated(S) {
var suffix = "- depreciated";
return S.indexOf(suffix, S.length - suffix.length) !== -1;
}
You could use currying: http://ejohn.org/blog/partial-functions-in-javascript/
Function.prototype.curry = function() {
var fn = this, args = Array.prototype.slice.call(arguments);
return function() {
return fn.apply(this, args.concat(
Array.prototype.slice.call(arguments)));
};
};
With the helper curry function you could create your isDepricated check:
String.prototype.isDepricated = String.prototype.match.curry(/- depreciated$/);
"string value - depreciated".isDepricated();
Or use .bind():
var isDepricated = RegExp.prototype.test.bind(/- depreciated$/);
isDepricated("string value - depreciated");
function isDepreciated(S){
return (new RegExp(" - depriciated$").test(S));
}
how about just use regular expression
var myRe=/depreciated$/;
var myval = "string value - depreciated";
if (myRe.exec(myval)) {
alert ('found');
}
else{
alert('not found');
}
lots of answers are already here (the one with $ is preferred), even though i also had to write one, so it will also do your job,
var somestring = "string value - depreciated";
var pattern="- depreciated";
function isDepreciated(var s)
{
b=s.substring(s.length-pattern.length,s.length)==pattern;
}
function isDeprecated(str) {
return ((str.indexOf("- depreciated") == str.length - "- depreciated".length) ? true : false);
}
isDeprecated("this")
false
isDeprecated("this - depreciated")
true
isDeprecated("this - depreciated abc")
false
Ok, I haven't run this code on a browser, but this should give a basic idea of what to do. You might have to tweak some of the conditions if needed.
var search = "- depricated";
var pos = str.indexOf(search);
if(pos > 0 && pos + search.length == str.length){
return true;
}
else{
return false;
}
Edit: indexOf() returns the start index of the string.

How can I validate image sizes (expressed as e.g. “5X4”) using JavaScript?

I have to do image size validation using JavaScript. The sizes are provided as text, in the form nXn — e.g. “5X4” or something.
I have done a test for whether the provided size contains an “X”:
if(inputVal.indexOf("X")==-1)
{
$('#erSize').append("*Size should be (e.g) 6X4");
}
But this test accepts e.g. “aXg” also.
How can I check that the values entered either side of "X" are only integers?
Use Regular Expressions
var pattern = /[0-9]\X[0-9]/;
inp = "AXG"; //Sample
if(!pattern.test(inp))
alert("Error");
http://jsfiddle.net/hFTJb/
if(/^\d+X\d+$/.test(inputVal)) // add i after the pattern to match x case-insensitive
{
$('#erSize').append("*Size should be (e.g) 6X4");
}
// accepts "1X1"
// accepts "9999X9999"
// rejects "aaa1X1aaa"
RegEx is probably the best way, I'll give "raw" example without regular expressions that is doing the same thing:
function ValidateImageSize(imgSize) {
var arrDimensions = imgSize.toUpperCase().split("X");
if (arrDimensions.length != 2)
return false;
var w = arrDimensions[0] * 1;
var h = arrDimensions[1] * 1;
return !isNaN(w) && !isNaN(h) && w > 0 && h > 0;
}
Usage:
if (!ValidateImageSize(inputVal)) {
$('#erSize').append("*Size should be (e.g) 6X4");
}
Giving it as it's more readable than RegEx and you can control and understand each step.
Live test case.
You can easily do that by using the RegEx.
Use the regular expression as /(\d+)X(\d+)/g
function isValidInput() {
var regex = new RegExp(/(\d+)X(\d+)/g);
var match = regex.exec(inputVal);
if (match == null) {
$('#erSize').append("*Size should be (e.g) 6X4");
} else {
// here 'match' will be an array of 2 numeric values [D,D] where d is an integer.
}
}

If else conditions in Javascript

I have topdatedata value as 222
I have these 3 conditions specified
if((topDateData<250)&&(topDateData>25))
{
alert('one');
}
else if((topDateData>300)&&(topDateData<300))
{
alert('Two');
}
else
{
alert('Three');
}
My questions is why is it getting the value as alert(3) and not alert(one)??
When explicitly setting the value to 222, I see 'one' get alerted: http://jsfiddle.net/Wvjfa/
You should debug your actual value ( alert(topDateData); if you like) and see if it really is what you think it is.
Beyond that, Matt Ball is right, your second condition is borked. Also lonesomeday and Kerry are right about your variable case not matching between your question and the posted code.
Javascript is case sensitive, is topdatedata = 222 or topDateData = 222?
it's much safer just to set one value - as you're second criteria looks dodgy
var topDateData = 222;
if(topDateData > 300)
{
alert('two');
}
else if(topDateData > 250)
{
alert('');
}
else if(topDateData > 25)
{
alert('One');
}
else
{
alert('Three');
}
start with the one that's hardest to satisfy (in this example the highest) and then work your way down. It's much easier to follow. Other than that it should work, as per the other comments on here
My guess is that you have a string.
var trueBool = '222' < '250'; //true
var falseBool = '222' > '25'; //false
To debug if topDateData is a String or not, do the following:
alert(topDateData + 1);//outputs '2221' if a string, and '223' if a number
Here's a fiddle showing the difference.
UPDATE:
I've tested alert(('222' < 250) && ('222' > 25)); and that outputs true. However, I'm not sure all JavaScript compilers will be smart enough to convert the string to a number first. You should run the same test and see if true is the output on your browser.
It looks like your topDateData variable contains a string value "222" instead of an integer.
You could try to cast to an integer this way:
topDateData = parseInt(topDateData);
...

How do I check if string contains substring? [duplicate]

This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 5 years ago.
I have a shopping cart that displays product options in a dropdown menu and if they select "yes", I want to make some other fields on the page visible.
The problem is that the shopping cart also includes the price modifier in the text, which can be different for each product. The following code works:
$(document).ready(function() {
$('select[id="Engraving"]').change(function() {
var str = $('select[id="Engraving"] option:selected').text();
if (str == "Yes (+ $6.95)") {
$('.engraving').show();
} else {
$('.engraving').hide();
}
});
});
However I would rather use something like this, which doesn't work:
$(document).ready(function() {
$('select[id="Engraving"]').change(function() {
var str = $('select[id="Engraving"] option:selected').text();
if (str *= "Yes") {
$('.engraving').show();
} else {
$('.engraving').hide();
}
});
});
I only want to perform the action if the selected option contains the word "Yes", and would ignore the price modifier.
Like this:
if (str.indexOf("Yes") >= 0)
...or you can use the tilde operator:
if (~str.indexOf("Yes"))
This works because indexOf() returns -1 if the string wasn't found at all.
Note that this is case-sensitive.
If you want a case-insensitive search, you can write
if (str.toLowerCase().indexOf("yes") >= 0)
Or:
if (/yes/i.test(str))
The latter is a regular expression or regex.
Regex breakdown:
/ indicates this is a regex
yes means that the regex will find those exact characters in that exact order
/ ends the regex
i sets the regex as case-insensitive
.test(str) determines if the regular expression matches str
To sum it up, it means it will see if it can find the letters y, e, and s in that exact order, case-insensitively, in the variable str
You could use search or match for this.
str.search( 'Yes' )
will return the position of the match, or -1 if it isn't found.
It's pretty late to write this answer, but I thought of including it anyhow. String.prototype now has a method includes which can check for substring. This method is case sensitive.
var str = 'It was a good date';
console.log(str.includes('good')); // shows true
console.log(str.includes('Good')); // shows false
To check for a substring, the following approach can be taken:
if (mainString.toLowerCase().includes(substringToCheck.toLowerCase())) {
// mainString contains substringToCheck
}
Check out the documentation to know more.
Another way:
var testStr = "This is a test";
if(testStr.contains("test")){
alert("String Found");
}
** Tested on Firefox, Safari 6 and Chrome 36 **
ECMAScript 6 introduces String.prototype.includes, previously named contains.
It can be used like this:
'foobar'.includes('foo'); // true
'foobar'.includes('baz'); // false
It also accepts an optional second argument which specifies the position at which to begin searching:
'foobar'.includes('foo', 1); // false
'foobar'.includes('bar', 1); // true
It can be polyfilled to make it work on old browsers.
The includes() method determines whether one string may be found within another string, returning true or false as appropriate.
Syntax :-string.includes(searchString[, position])
searchString:-A string to be searched for within this string.
position:-Optional. The position in this string at which to begin searching for searchString; defaults to 0.
string = 'LOL';
console.log(string.includes('lol')); // returns false
console.log(string.includes('LOL')); // returns true
You can use this Polyfill in ie and chrome
if (!('contains' in String.prototype)) {
String.prototype.contains = function (str, startIndex) {
"use strict";
return -1 !== String.prototype.indexOf.call(this, str, startIndex);
};
}
If you are capable of using libraries, you may find that Lo-Dash JS library is quite useful. In this case, go ahead and check _.contains() (replaced by _.includes() as of v4).
(Note Lo-Dash convention is naming the library object _.
Don't forget to check installation in the same page to set it up for your project.)
_.contains("foo", "oo"); // → true
_.contains("foo", "bar"); // → false
// Equivalent with:
_("foo").contains("oo"); // → true
_("foo").contains("bar"); // → false
In your case, go ahead and use:
_.contains(str, "Yes");
// or:
_(str).contains("Yes");
..whichever one you like better.
I know that best way is str.indexOf(s) !== -1; http://hayageek.com/javascript-string-contains/
I suggest another way(str.replace(s1, "") !== str):
var str = "Hello World!", s1 = "ello", s2 = "elloo";
alert(str.replace(s1, "") !== str);
alert(str.replace(s2, "") !== str);
You can also check if the exact word is contained in a string. E.g.:
function containsWord(haystack, needle) {
return (" " + haystack + " ").indexOf(" " + needle + " ") !== -1;
}
Usage:
containsWord("red green blue", "red"); // true
containsWord("red green blue", "green"); // true
containsWord("red green blue", "blue"); // true
containsWord("red green blue", "yellow"); // false
This is how jQuery does its hasClass method.
you can define an extension method and use it later.
String.prototype.contains = function(it)
{
return this.indexOf(it) != -1;
};
so that you can use in your page anywhere like:
var str="hello how are you";
str.contains("are");
which returns true.
Refer below post for more extension helper methods.
Javascript helper methods
None of the above worked for me as there were blank spaces but this is what I did
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
bottab.style.display="none";
bottab2.style.display="none";
if (td) {
var getvar=td.outerText.replace(/\s+/, "") ;
if (getvar==filter){
tr[i].style.display = "";
}else{
tr[i].style.display = "none";
}
}
}

JavaScript or jQuery string ends with utility function

what is the easiest way to figure out if a string ends with a certain value?
you could use Regexps, like this:
str.match(/value$/)
which would return true if the string has 'value' at the end of it ($).
Stolen from prototypejs:
String.prototype.endsWith = function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
};
'slaughter'.endsWith('laughter');
// -> true
Regular expressions
"Hello world".match(/world$/)
I had no luck with the match approach, but this worked:
If you have the string, "This is my string." and wanted to see if it ends with a period, do this:
var myString = "This is my string.";
var stringCheck = ".";
var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0;
alert(foundIt);
You can change the variable stringCheck to be any string to check for. Better still would be to throw this in your own function like this:
function DoesStringEndWith(myString, stringCheck)
{
var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0;
return foundIt;
}
You can do 'hello world'.slice(-5)==='world'. Works in all browsers. Much faster than regex.
ES6 supports this directly:
'this is dog'.endsWith('dog') //true
I am just expanding on what #luca-matteis has posted but to solve the issues pointed out in the comments the code should be wrapped to make sure you are not overwriting a native implementation.
if ( !String.prototype.endsWith ) {
String.prototype.endsWith = function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
};
}
This is the suggested method for the Array.prototype.forEach method pointed out in the mozilla developer network
You can always prototype String class, this will work:
String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}
You can find other related extensions for String class in http://www.tek-tips.com/faqs.cfm?fid=6620

Categories