Is there a way to programmatically check whether a filter with a given name exists?
I developed a directive to process page content based on a string input, I want it to react differently in case a certain part of the string corresponds to a filter that exists in my system. For example I have a localize filter:
// Somewhere in the code
var myInput = 'localize';
// Somewhere else
var contentToProcess = 'my content';
var result = '';
if ($filter.hasOwnProperty(myInput)) // TODO: this is the part I'm trying to figure out
result = $filter(myInput)(contentToProcess);
else
result = 'something else';
Jonathan's answers is also acceptable, but I wanted to find a way to check if a filter exists without using a try catch.
You can see if a filter exists like this:
return $injector.has(filterName + 'Filter');
The 'Filter' suffix is added by angular internally, so you must remember to add it or you will always return false
Solution
This seems to work for me.
var getFilterIfExists = function(filterName){
try {
return $filter(filterName);
} catch (e){
return null;
}
};
Then you can do a simple if check on the return value.
// Somewhere in the code
var myInput = 'localize';
var filter = getFilterIfExists(myInput);
if (filter) { // Check if this is filter name or a filter string
value = filter(value);
}
Bonus
If you are looking to parse apart a filter string for example 'currency:"USD$":0' you can use the following
var value; // the value to run the filter on
// Get the filter params out using a regex
var re = /([^:]*):([^:]*):?([\s\S]+)?/;
var matches;
if ((matches = re.exec(myInput)) !== null) {
// View your result using the matches-variable.
// eg matches[0] etc.
value = $filter(matches[1])(value, matches[2], matches[3]);
}
Pull it all together
Wish there was a more elegant way of doing this with angular however there doesn't seem to be.
// Somewhere in the code
var myInput = 'localize';
var value; // the value to run the filter on
var getFilterIfExists = function(filterName){
try {
return $filter(filterName);
} catch (e){
return null;
}
};
var filter = getFilterIfExists(this.col.cellFilter);
if (filter) { // Check if this is filter name or a filter string
value = filter(value);
} else {
// Get the filter params out using a regex
// Test out this regex here https://regex101.com/r/rC5eR5/2
var re = /([^:]*):([^:]*):?([\s\S]+)?/;
var matches;
if ((matches = re.exec(myInput)) !== null) {
// View your result using the matches-variable.
// eg matches[0] etc.
value = $filter(matches[1])(value, matches[2], matches[3]);
}
}
You can just do this:
var filter = $filter(myInput);
if (filter)
result = filter(contentToProcess);
else
result = 'something else';
Undefined and null values are treated as false in JS, so this should work in your case.
Related
Question: I am trying to validate email endings in an array
let input = 'test#gmail.com' // This is grabbed dynamically but for sake of explanation this works the same
let validEndings = ['#gmail.com', '#mail.com', '#aol.com'] //and so on
if(input.endsWith(validEndings)){
console.log('valid')
}else{
console.log('invalid')
}
I can get this to work when validEndings is just a singular string e.g let validEndings = '#gmail.com'
but not when its in an array comparing multiple things
You can solve the problem with regex. Example:
const input = 'test#gmail.com';
const validEndingsRegex = /#gmail.com$|#mail.com$|#aol.com$/g;
const found = input.match(validEndingsRegex);
if (found !== null) {
console.log('valid')
} else {
console.log('invalid')
}
You can achieve this by using Array.some() method which tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false.
Live Demo :
let input = 'test#gmail.com';
let validEndings = ['#gmail.com', '#mail.com', '#aol.com'];
const res = validEndings.some(endingStr => input.endsWith(endingStr));
console.log(res);
How can I add an "else" statement to the following dictionary with key/value pairs to handle any sort of ambiguity?
var inputArr = input.match(/[\d.]+/g).map(Number);
var inputAnswer = ""
inputArr.forEach(function(element, index){
var lookUp = {
"1":"611"
"2":"612"
"3":"613"
"":""
};
inputAnswer = lookUp[element];
}
return inputAnswer
});
As you can see, the key/value pairs are only programmed to handle "1","2","3", and "". How can I add another value to it which would return blank string ("") if it is passed any other value? Just want it to be dynamically set up to handle any sort of data. Thanks!
Using a simple ternary, combined with hasOwnProperty will let you do what you want.
Note: using a simple || check may not give the desired results, as it will return '' if falsey value is set in the lookUp object. For a demo of why / how this may not do what you expect, see this fiddle
var inputArr = input.match(/[\d.]+/g).map(Number);
var inputAnswer = ""
inputArr.forEach(function(element, index) {
var lookUp = {
"1":"611"
"2":"612"
"3":"613"
"":""
};
// If a defined value exists, return it, otherwise ''
inputAnswer = ( lookUp.hasOwnProperty(element) ) ? lookUp[element] : '';
}
return inputAnswer
});
I've read some question but I still can't figure out how to do it
I have a url example.com/event/14aD9Uxp?p=10
Here I want to get the 14aD9Uxp and the value of p
I've tried using split('/'+'?p=') but it doesn't work
I want to use regex but I dont really understand how to use it
var URL='example.com/event/14aD9Uxp?p=10';
var arr=URL.split('/');//arr[0]='example.com'
//arr[1]='event'
//arr[2]='14aD9Uxp?p=10'
var parameter=arr[arr.length-1].split('?');//parameter[0]='14aD9Uxp'
//parameter[1]='p=10'
var p_value=parameter[1].split('=')[1];//p_value='10';
I've created a generalized function (restricted in some ways) that will return the GET value given the parameter. However this function will only work correctly provided that you do not Rewrite the URL or modify the URL GET SYNTAX.
//Suppose this is your URL "example.com/event/14aD9Uxp?p=10";
function GET(variable) {
var str = window.location.href;
str = str.split("/");
// str = [example.com, event, 14aD9Uxp?p=10]
//Get last item from array because this is usually where the GET parameter is located, then split with "?"
str = str[str.length - 1].split("?");
// str[str.length - 1] = "14aD9Uxp?p=10"
// str[str.length - 1].split("?") = [14aD9Uxp, p=10]
// If there is more than 1 GET parameter, they usually connected with Ampersand symbol (&). Assuming there is more, we need to split this into another array
str = str[1].split("&");
// Suppose this is your URL: example.com/event/14aD9Uxp?p=10&q=112&r=119
// str = [p=10, q=112, r=119]
// If there is only 1 GET parameter, this split() function will not "split" anything
//Remember, there might only be 1 GET Parameter, so lets check length of the array to be sure.
if (str.length > 1) {
// This is the case where there is more than 1 parameter, so we loop over the array and filter out the variable requested
for (var i = 0; i < str.length; i++) {
// For each "p=10" etc. split the equal sign
var param_full_str = str[i].split("=");
// param_full_str = [p, 10]
//Check if the first item in the array (your GET parameter) is equal to the parameter requested
if (param_full_str[0] == variable) {
// If it is equal, return the second item in the array, your GET parameter VALUE
return param_full_str[1];
}
}
} else {
// This is the case where there is ONLY 1 GET parameter. First convert it to a String Type because Javascript decided that str was no longer a String
// Now split it with the equal sign.
str = str.toString().split("=");
return str[1];
}
}
document.write(GET("p"));
function $_GET(param) {
var vars = {};
window.location.href.replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}
I have collected this from here:
http://www.creativejuiz.fr/blog/javascript/recuperer-parametres-get-url-javascript
It works great.
To use it just grab your parameter like:
var id = $_GET('id');
const url = new URL('http://example.com/event/14aD9Uxp?p=10');
const [,, eventId ] = url.pathname.split('/');
const p = url.searchParams.get('p');
Browser support:
https://caniuse.com/#feat=url
https://caniuse.com/#feat=urlsearchparams
Simple no-regex way
var s = "example.com/event/14aD9Uxp?p=10";
var splitByForwardSlash = s.split('/');
// To get 14aD9Uxp
splitByForwardSlash[splitByForwardSlash.length-1]
// To get p=10
splitByForwardSlash[splitByForwardSlash.length-1].split('?')[1]
I think you know how to go from here :-)
I'm trying to figure out the workings of a neat jQuery based library called selectize.js.
On the demos-page they have an example of the "createFilter" function, which I want to use to check whether the user input already exist, and if not, create the item.
The example from selectize.js (meant for e-mail):
createFilter: function(input) {
var match, regex;
// email#address.com
regex = new RegExp('^' + REGEX_EMAIL + '$', 'i');
match = input.match(regex);
if (match) return !this.options.hasOwnProperty(match[0]);
// name <email#address.com>
regex = new RegExp('^([^<]*)\<' + REGEX_EMAIL + '\>$', 'i');
match = input.match(regex);
if (match) return !this.options.hasOwnProperty(match[2]);
return false;
},
My own take on making a filter to only allow letters, and check if it's already in the list:
createFilter: function (input) {
var match, regex;
regex = new RegExp('^[a-zA-ZæøåÆØÅ][a-zA-ZæøåÆØÅ ]*[a-zA-ZæøåÆØÅ]$', 'i');
match = input.match(regex);
if (match) return !this.options.hasOwnProperty(match[0]);
return false;
},
For some reason it always returns true thus allowing the user to add a new item, even though it already exists, after hours of testing, I'm convinced it has something to do with this.options.hasOwnProperty - but I'm at a dead end figuring out what and why, any help or guidance would be greatly appreciated.
I have been trying to get the createFilter to work as well, and looked into the source, but things seems setup properly but there is a clearly a bug in there somewhere. For now my solution was the use of the actual create method. If you dig a bit in the source (alluded to by the documentation on the create option) you will notice that prior to item creation it will check if your value of create is a function:
var setup = (typeof self.settings.create === 'function') ? this.settings.create : function(input) {
var data = {};
data[self.settings.labelField] = input;
data[self.settings.valueField] = input;
return data;
};
By passing in a creation function that only returns a value for data when a certain condition is passed, else it returns {}, you can effectively do exactly what you wanted to do in the createFilter function.
$('#foo').selectize({
create: function(input){
var self = this;
var data = {};
// IF SOME CONDITION MET
if (bar) {
data[self.settings.labelField] = input;
data[self.settings.valueField] = input;
}
return data;
},
});
If data is returned as {}, the item is not created and the user can continue to modify it as needed (or be informed that there selection was invalid).
I'm trying to extract a URL from an array using JS but my code doesn't seem to be returning anything.
Would appreciate any help!
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
function url1_m1(pages, pattern) {
var URL = '' // variable ready to accept URL
for (var i = 0; i < pages[i].length; i++) {
// for each character in the chosen page
if (pages[i].substr(i, 4) == "www.") {
// check to see if a URL is there
while (pages[i].substr(i, 1) != "|") {
// if so then lets assemble the URL up to the colon
URL = URL + pages[i].substr(i, 1);
i++;
}
}
}
return (URL);
// let the user know the result
}
alert(url1_m1(pages, "twitter")); // should return www.twitter.com
In your case you can use this:
var page = "www.facebook.com|Facebook";
alert(page.match(/^[^|]+/)[0]);
You can see this here
It's just example of usage RegExp above. Full your code is:
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
var parseUrl = function(url){
return url.match(/^(www\.[^|]+)+/)[0];
};
var getUrl = function(param){
param = param.toLowerCase();
var page = _(pages).detect(function(page){
return page.toLowerCase().search(param)+1 !== 0;
});
return parseUrl(page);
};
alert(getUrl('twitter'));
You can test it here
In my code I have used Underscore library. You can replace it by standard for or while loops for find some array item.
And of course improve my code by some validations - for example, for undefined value, or if values in array are incorrect or something else.
Good luck!
Im not sure exactly what you are trying to do, but you could use split() function
var pair = pages[i].split("|");
var url = pair[0], title=pair[1];