Email Protected Webpage [duplicate] - javascript

I learning ES6 and try to use new for me endsWith. Before this I used includes in some of my scripts, and I thought that mechanic will be same. I picked a casual task: I have domains list and want to filter all "cn" domains. Logic is:
let ends = [".cn",".tw",".jp"]
for(let i=0;i<arrayOfDomains.length;i++){
const host = /https?:\/\/(www\.)?([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]+/.exec(arrayOfDomains[i])[0];
console.log(host.endsWith(ends))
}
and result of console.log all false. Is there a way to use array in endsWith?

No, there isn't a way to use an array in endsWith, one option is to declare another function that uses the ends array and host variable as parameters to check it.
You can try something like this:
let ends = [".cs", ".com"];
let host = "www.page.com";
let hostEndsWith = (host, ends) => {
let value = false;
value = ends.some(element => {
return host.endsWith(element);
});
console.log(value);
};
hostEndsWith(host, ends);
You can copy that code in JSFiddle to test it.
Here is the information about the endsWith function endsWith informartion
I hope this helps you!

Related

extract sections of string with JavaScript

Suppose I have a string variable {{Name}} that looks like this:
APPLE-CARROT-PAPER-HILL
I want to create 4 variables using JavaScript that captures each piece:
var1 = APPLE
var2 = CARROT
var3 = PAPER
var4 = HILL
In Tag Manager, I assume the JS for var1 would be:
function(){
var name = {{Name}}.slice(0, {{Name}}.indexOf("-"));
return name;
}
but how then to do the others?
Not sure what You are wanting to do, but it's easier and better to:
Store all the values in one array, not separate vars.
Use split instead of complicated function to extract them.
var str = 'APPLE-CARROT-PAPER-HILL';
console.log(str.split('-'));
var name_str = "APPLE-CARROT-PAPER-HILL";
function a(){
var v1, v2, v3, v4;
var name = name_str.split('-');
[v1, v2, v3, v4] = name;
console.log(v1);
console.log(v2);
console.log(v3);
console.log(v4);
}
a();
Since you are using GTM (so far the other answers have ignored the google-tag-manager tag), I suspect your actual question is if there is a way to solve this with a single variable. Alas, no, you need to create a variable for each piece of your string
APPLE-CARROT-PAPER-HILL
// Apple
function(){
return {{Name}}.split("-")[0];
}
// Carrot
function(){
return {{Name}}.split("-")[1];
}
etc.
You can make this a bit nicer but creating a custom template that returns the value for a given index from an array, but if you want to use the parts of the name in separate fields (e.g. for use as custom dimensions) then alas you need a variable for each segment of your delimited string.
Try This,
let name = 'APPLE-CARROT-PAPER-HILL';
let nameAr = name.split('-');
let var1 = nameAr[0];
let var2 = nameAr[1];
let var3 = nameAr[2];
let var4 = nameAr[3];
I hope this code helping you
var name = "APPLE-CARROT-PAPER-HILL"
name.split("-")

How to replace 2 values at one replace call

So i am wondering how i can replace two or more at once with single replace call.
I haven't tried anything so far, as i don't have a clue how i can do that.
let links = {
_init: "https://%s.website.com/get/%s",
}
So as you can see here i have a link with 2x %s which i want to replace.
I am thinking about something like this:
links._init.replace('%s', 'name', 'query')
obviously it won't work. So i am wondering if there is other way of doing it.
I know that languages like python, c# etc have similar feature.
One option is to use a replacer function, and an array that you shift() from:
let links = {
_init: "https://%s.website.com/get/%s"
};
const replaceWith = ['name', 'query'];
const replaced = links._init.replace(
/%s/g,
() => replaceWith.shift()
);
console.log(replaced);
If you don't want to mutate the existing array, you can also use a counter that gets incremented on every iteration:
let links = {
_init: "https://%s.website.com/get/%s"
};
const replaceWith = ['name', 'query'];
let i = 0;
const replaced = links._init.replace(
/%s/g,
() => replaceWith[i++]
);
console.log(replaced);

Search in a Jquery object for multiple strings stored in an array

I'm not entirely sure if the title of my question makes any sense but I'll try and explain it further as I'm struggling to get this code working.
I'm scanning through a page for any script tags and I then extract the src values of them. All I want to do now is to check if the Jquery object has either of the two specific directories within it. If it does then I will do some other work with them. My code so far looks like this;
var scriptTags = $('script');
var directoryNames = ['abc/custom','xyz/custom'];
for (var i = 0; i < scriptTags.length; i++) {
var srcVal = scriptTags[i].src;
if (ANY DIRECTORY NAME VALUES FOUND WITHIN scriptTags) {
console.log('found');
}
}
I'd really appreciate if anyone could shed some light on this,please?
Thanks.
You're looking for directoryNames.indexOf(srcVal).
The indexOf function will return the index in the array of the element that was found (srcVal) and if it's not found it'll return -1.
End product:
if(directoryNames.indexOf(srcVal) > -1) ...
if(directoryNames.some(name => srcVal.includes(name)))
Just go over all directory names and check if they are part of the current url. Or if you got a lot of urls it might be better to build a tree of directories:
const root = {};
for(const url of directoryNames) {
let acc = root;
for(const path of url.split("/")) {
acc = acc[path] = acc[patch] || {};
}
acc.isEnd= true;
}
So then you can check an url with:
if(srcVal.split("/").reduce((acc, path) => acc[path] || {}, root).isEnd)

delete a Object from an Array stored in localStorage on a specific condition?

I have stored certain information in localStorage like-
$localStorage.recent = [{'id':1,'name':'abc','is_availbale':1},{'id':2,'name':'xyz','is_availbale':1},{'id':3,'name':'pqrs','is_availbale':0}];
having another array which is only having id's of certain people like(array_second can have only those id's which are already there in
$localStorage.recent)-
array_second=['3'];
I want to delete those entries from $localStorage.recent which are corresponding to the id's in array_second. Expected output to be-
$localStorage.recent = [{'id':1,'name':'abc','is_availbale':1},{'id':2,'name':'xyz','is_availbale':1}];
You're just handling a standard array. The ngstorage library doesn't give you any additional functionality here.
For example:
$localStorage.recent = $localStorage.recent.filter((person) => {
return second_array.indexOf(person.id) !== -1;
});
This code may useful to you, written in javascript
var fullArr =[{'id':1,'name':'abc','is_availbale':1{'id':2,'name':'xyz','is_availbale':1},{'id':3,'name':'pqrs','is_availbale':0}];
var toDelArr = [1];
for(var i=0;i<fullArr.length;i++){
if(toDelArr[0] == fullArr[i].id){
fullArr.splice(i, 1);
}
}

Issue with JSON stringify?

/* Helper function to clean up any current data we have stored */
function insertSerializedData(ids, type) {
// Get anything in the current field
current_data = $('#changes').val();
if (!current_data) {
var data = new Array();
data[type] = ids;
$('#changes').val(JSON.stringify(data));
} else {
var data = JSON.parse($('#changes').val());
data[type] = ids;
$('#changes').val(JSON.stringify(data));
}
console.log($('#changes').val());
}
I am using the following function to either add data to a current JSON object or create a new JSON object all together to be used in PHP later. Is the stringify() method only for FF? I am using google chrome and I am being given an empty object when using the conosole.log() function...
Also what happens if you try to store two values with the same key? I assume it will overwrite...so I should add a random math number at the end array in order to keep duplicates from showing up?
Thanks :)
These lines may cause problems:
var data = new Array();
data[type] = ids;
... because arrays in JavaScript are not quite like arrays in PHP. I suppose what you meant is better expressed by...
var data = {};
data[type] = ids;
Besides, current_data seems to be local to this function, therefore it also should be declared as local with var. Don't see any other problems... except that similar functionality is already implemented in jQuery .data() method.
UPDATE: here's jsFiddle to play with. ) From what I've tried looks like the array-object mismatch is what actually caused that Chrome behavior.
I reformatted it a bit, but and this seems to work. It will set the "value" attribute of the #changes element to a JSON string. I assume that the type argument is supposed to be the index of the array which you're trying to assign?
function insertSerializedData(ids, type) {
var changes = jQuery('#changes'), arr, val = changes.val();
if (!val) {
arr = [];
arr[type] = ids;
changes.val(JSON.stringify(arr));
} else {
arr = JSON.parse(val);
arr[type] = ids;
changes.val(JSON.stringify(arr));
}
console.log(changes);
}

Categories

Resources