Check pathname for Array - javascript

i got a question:
This code snippet works great:
$(document).ready(function(){
var pathname = window.location.pathname;
if(pathname.indexOf( 'word1' ) > -1){
// do something
}
});
But if i want to check for array of word´s it doesnt work:
$(document).ready(function(){
var myArray1 = new Array( "word1","word2","word3","word4" );
var pathname = window.location.pathname;
if(pathname.indexOf( myArray1 ) > -1){
// never executed! why?
}
});
Anybody could help with this problem? Greetings!

jQuery has a built in method for that, $.inArray :
$(document).ready(function(){
var pathname = window.location.pathname;
if ( $.inArray(pathname, ["word1","word2","word3","word4"] ) != -1 ) {
// do stuff
}
});
then there's regex
$(document).ready(function(){
if ( /(word1|word2|word3|word4)/.test(window.location.pathname) ) {
// do stuff
}
});

If you want to test pathname against an array of values, I suggest looping. You cannot send in an array object as an argument to the indexOf() method. You can only send strings.
$(document).ready(function(){
var myArray1 = new Array( "word1","word2","word3","word4" );
var pathname = window.location.pathname;
for(stringy in myArray1){
if(pathname.indexOf( stringy ) > -1){
console.log('Match Found');
}
}
});
Look here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

You could use jQuery.grep() for this:
if ($.grep(myArray1, function(word) {
return pathname.indexOf(word) != -1;
})) {
// do something
}
Or, use native functions:
if (myArray1.some(function(word) {
return pathname.indexOf(word) != -1;
})) {
// do something
}

indexOf looks for occurrences of a given string in another string. So you can't invoke it with an array as parameter. You must invoke it several times, each one with a string as parameter.
$(document).ready(function(){
var myArray1 = new Array( "word1","word2","word3","word4" );
var pathname = window.location.pathname;
for(var i=0; i<myArray1.length; i++) {
if(pathname.indexOf( myArray1[i] ) > -1){
// will be executed
}
}
});

string.indexOf doesn't take array as a parameter, you should handle it yourself,
Ok I will make it a little bit different, you can also do this with Regex,
$(document).ready(function(){
var myArray1 = new Array( "word1","word2","word3","word4" );
var pathname = window.location.pathname;
if (pathname.match(new RegExp(myArray1.join("|")))) {
// yes, there is at least one match.
}
});
I don't know whether if you want it to match all words in the array.

I made a way to test n quantities of pathnames.
import pathToRegexp from 'path-to-regexp';
const ALLOWED_PATHS = [
'test',
'test/:param'
]
const allowed = ALLOWED_PATHS.map((path) => {
const regex = pathToRegexp(path)
return regex.test(window.location.pathname);
});
if(allowed.some(Boolean)) {
// Match
} else {
// Not Match
}
...
Hope this helps you!

Related

How to get false when match finds nothing?

When I run this code:
var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = foundUrlString[1];
I get an error if there are no matches on the page:
Result of expression 'foundUrlString' [null] is not an object
How can I get "false" when there are no matches instead of this error?
Going off of what you have, you could add a "truthy" check on the second line:
var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = !!foundUrlString && foundUrlString[1];
That will leave foundUrl either as a matched string or false.
Check null to print false or true.
var savedPage = '';
var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = foundUrlString == null ? false : true;
console.log(foundUrl );
Here is an example with try and catch which may help you:
function regex(savedPage) {
try {
var foundUrlString = savedPage.match(/og:url.*="(http.*\.com)/i);
return foundUrlString[1];
} catch (error) {
return false;
}
}
var savedPage1 = '<link property="og:url" content="http://test.com/test">';
console.log('savedPage1',regex(savedPage1));
var savedPage2 = '<link content="http://test.com/test">';
console.log('savedPage2',regex(savedPage2));
You need to understand what's the purpose of String.prototype.match. The function match will return an array with the whole set of matched groups in your regexp. So, if you want to validate a string, the best way is using the function RegExp.prototype.test.
Use the function RegExp.prototype.test from regexp:
let savedPage = "EleFromStack";
console.log(/og:url.*="(http.*\.com)/i.test(savedPage));

Matching a string to an array

I need your your help,
For some strange reason, when my var str is set to "OTHER-REQUEST-ASFA" the matched key comes back as "ASF" as opposed to "ASFA"
How can I get the returned output key of "ASFA" when my str is "OTHER-REQUEST-ASFA"
function test() {
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
for (var key in filenames) {
if (str.indexOf(key) != -1) { alert(filenames[key]) }
}
}
You could switch from
str.indexOf(key)
to
key.indexOf(str)
function test() {
var str = "OTHER-REQUEST-ASFA",
filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
},
key;
for (key in filenames) {
if (key.indexOf(str) != -1) {
console.log(filenames[key]);
}
}
}
test();
To answer why it's not working as you want...
You've got:
str.indexOf(key)
This checks for the first instance of key in str.
So in your loop, key first equals OTHER-REQUEST-ASF which is part of OTHER-REQUEST-ASFA, so the condition is true.
However, to do what you want to do, if you know the pattern is always going to be OTHER-REQUEST-XYZ, the easiest way is to use split():
str.split('-')[2]
will always return the last section after the last -
cause "OTHER-REQUEST-ASFA".indexOf("OTHER-REQUEST-ASF") will not return -1, so it will show "ASF"
You can also use static method Object.keys() to abtain array of keys
var test = () =>{
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
Object.keys(filenames).forEach(x => {
if ( x.indexOf(str) !== -1)
console.log(filenames[str]);
});
}
test();

using match(), but it didn't work froma string variable

I have the following fiddle:
jsfiddle
The function:
$('#testbutton').on("click", function(){
test();
});
function test()
{
var data = [];
data['article'] = "monablanko";
data['specialarticle'] = ["blanko", "bbsooel"];
var tmp = data['specialarticle'].join("|");
if( data['article'].match( /(tmp)/ ) )
{
$('#result').html("I found a match");
}
else
{
$('#result').html("I didn't found a match");
}
}
I didn't found a match with this function. Where is my error? The typeof tmp is string when i use
console.log(typeof tmp);
when i write
if( data['article'].match( /(blanko|bbsooel)/ ) )
then i find a match.
You're matching against the string literal "tmp", not against the value contained inside the variable tmp. Try it like this:
data['article'].match( new RegExp("(" + tmp + ")") )
eg: http://jsfiddle.net/4K8Km/
You need to create a RegExp to match your string before:
$('#testbutton').on("click", function(){
test();
});
function test(){
var data = [];
data['article'] = "monablanko";
data['specialarticle'] = ["blanko", "bbsooel"];
var tmp = new RegExp('('+data['specialarticle'].join("|")+')');
if( data['article'].match( tmp ) )
{
$('#result').html("I found a match");
}
else
{
$('#result').html("I didn't found a match");
}
}
Just one more tip: if you don't need to collect a match, but just to test if the string has that RegExp I would suggest to use test instead of match:
tmp.test(data['article']);
rather than
data['article'].match(tmp);

Find an element exist in List using jQuery

I am pretty much working on the basics of jQuery, it could have done easily if it's in Java :P
var thread_list = [];
var feed_list = [];
$.each(json.messages, function(i, m) {
if (m.replied_to_id == "") {
alert(m.thread_id);
thread_list.push(m.thread_id);
}
});
$.each(json.references, function(i, r) {
if (r.id exists in threadList) { //how do I do this more effectively?
feed_list.push(r.url);
}
});
How to find an element exist in the List?
In a modern browser you could use the filter function on [].
var thread_list = [{id:1},{id:2},{id:3}];
var feed_list = [];
function exists(arr,prop,val){
var threads = arr.filter(function(e){
return e[prop] == val;
});
return !!threads.length;
}
alert(exists(thread_list, "id", 4)); //returns false
alert(exists(thread_list, "id", 2)); //returns true
JS FIDDLE: http://jsfiddle.net/7vTWj/
jQuery.inArray(r.id , threadList); //give 0 to any positive number if exist otherwise give -1
reference inarray
Try this:
$.each(json.references, function(i, r) {
if (threadlist.indexOf(r)!=-1) {
feed_list.push(r.url);
}
});
In java, actually you would create a JSONOBject for the original json and then get the json threadlist as a JSONArray and then convert it to an actual array to check it.
You can simply use
if ( $.inArray(r.id, threadList ) != 1 )
Use indexOf():
if (threadList.indexOf(r.id) != -1)
In case you're using an old browser that doesn't have indexOf(), you can use jQuery.inArray():
if ($.inArray(r.id, threadList) != -1)

to get a list of bools, .contain()

how do i do a list for bools in javascript. im doing a validation so i can have a list of bools and at the end i want to check that list if it contains any errors. im not sure how to add to the varable validations_errors (like a list). Plus i dont know how i can check if that list contains any true values.
what i got so far is this
var validation_errors;
if (!validateForm($(this))) {
validation_errors = false; //here i want to add the it to a list
var $input_container = $(this).parents('.input');
$input_container.removeClass('success').addClass('error');
}
//this is something what i want to do like (this code is c# based)
if (validation_errors.contains(true)){
// do some actions
}
EDIT
list of bools = list of true & false
validation_errors = []; // DECLARATION
validation_errors.push( newBool ); // adding a new val to the array.
And then you can regularly iterate through the array at the end.
If I were you though, I would try something like this...
validation_errors = false; // declaration
Within the loop
If ( !newBool ) validation_errors = true;
And at the end
If( validation_errors ) //we failed
So you won't need a whole array and a second loop.
Edit : cellphone typing
var validation_errors = [];
.
.
.
if (error) validation_errors.push(true)
if (validation_errors.length > 0) ...
If you want to store true or false so you can use indexOf to find which test failed:
if (validateForm($(this))) validation_errors.push(false);
else {
validation_errors.push(true);
var $input_container = $(this).parents('.input');
$input_container.removeClass('success').addClass('error');
}
var notvalid = validation_errors.indexOf(true);
if (notValid !=-1) alert("The form #"+(notvalid+1)+" failed")
Make validation_errors an array and push the result of your validation into the array. If you don't check for failed validations (i.e. get rid of the ! in your first if statement), the validation_errors array will contain true only if validateForm returns true:
var validation_errors = [];
if(validateForm($(this))) {
validation_errors.push(false);
}
else {
var $input_container = $(this).parents('.input');
$input_container.removeClass('success').addClass('error');
}
if(validationErrors.length > 0) {
//Do some actions
}
Alternatively (as I'm not 100% clear on what you're trying to do), you could just use a string:
var validation_errors = "";
if(validateForm($(this))) {
validation_errors = "true";
}
else {
var $input_container = $(this).parents('.input');
$input_container.removeClass('success').addClass('error');
}
if(validation_errors = "true") {
//Do some actions
}

Categories