Javascript .split () function with multiple conditions [duplicate] - javascript

This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
Closed 6 years ago.
Hey there I am having some troubles working with the split function within GTM, I want to read the body class and return a singular word. e.i.
<body class="landing-holidays subscribe-page"></body>
Returning just 'holidays', my challenge is to get the split to just pull the second value. Code:
function () {
var product = document.getElementsByTagName('body')[0];
if (product != undefined) {
var product_id = product.getAttribute('class');
if (product_id != null)
return product_id.split('-')[1];
}
return null
}
I get "holidays subscribe". When I need "holidays", any insight?

You can use a regular expresion. change .split('-') to .split(/[\-\s]/)
var product = document.getElementsByTagName('div')[0];
function run() {
if (product != undefined) {
var product_id = product.getAttribute('class');
if (product_id != null) {
var a = product_id.split(/[\-\s]/);
for (var i = 0, l = a.length; i < l; i++) {
if (a[i] === 'holidays') {
return a[i];
}
}
}
}
}
alert(run())
<div class="landing-holidays subscribe-page"></div>

Related

Check if string contains any of array of strings without regExp [duplicate]

This question already has answers here:
How to do case insensitive string comparison?
(23 answers)
How to check if a string contains text from an array of substrings in JavaScript?
(24 answers)
Closed 5 years ago.
I am checking a string input whether it contains any of an array of strings or not. It is passing most of the tests but not the below one.
Can anyone break my code down why it is not working properly?
function checkInput(input, words) {
var arr = input.toLowerCase().split(" ");
var i, j;
var matches = 0;
for(i = 0; i < arr.length; i++) {
for(j = 0; j < words.length; j++) {
if(arr[i] == words[j]) {
matches++;
}
}
}
if(matches > 0) {
return true;
} else {
return false;
}
};
checkInput("Visiting new places is fun.", ["aces"]); // returns false // code is passing from this test
checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"])); // returns false; should be returning true;
Thank you for your time!
You can use functional methods for this. Try Array.some.
const words = ['matters', 'definitely'];
const input = '"Definitely," he said in a matter-of-fact tone.';
console.log(words.some(word => input.includes(word)));
You can use array#includes to check if a word exist in your input and convert both your input and words in lower case and then use array#includes.
function checkInput(input, words) {
return words.some(word => input.toLowerCase().includes(word.toLowerCase()));
}
console.log(checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"]));
You can create regular expression and use i flag to specify case-insensitivity
function checkInput(input, words) {
return words.some(word => new RegExp(word, "i").test(input));
}
console.log(checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"]));

Comparison an array in java script [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have problem regarding how to compare string in an array..
in my list have jack,john,nami#domain,nami
function **alreadyInList**(list, toBeAdded) {
// return true or false
var delims = "(,)";
var tokens = list.split(delims);
for ( var i = 0; i < tokens.length; i++){
if (tokens[i] === toBeAdded ){
return true;
}
else
return false;
}
}
function addListTo(selectbox, textbox) {
var values = new Array();
var c = 0;
for ( i = 0; i < selectbox.options.length; i++) {
if (selectbox.options[i].selected) {
if (!**alreadyInList**(textbox.value,selectbox.options[i].value)) {
values[c++] = selectbox.options[i].value;
}
}
}
if (values.length == 0) return;
var v = values[0];
for (i = 1; i < values.length; i++) {
v += ',' + values[i];
}
if (textbox.value.length>0) {
if (textbox.value=='Any') {
textbox.value = v;
} else {
textbox.value += ',';
textbox.value += v;
}
} else {
textbox.value += v;
}
}
when i put my condition and i want to add the string into textbox it only work for the first string lets say i put nami as my string then when i want to put nami again it cannot so it works..but after "," i put name#domain .i can put back nami..means i dont want to repetitive string inside my textbox.can someone help me.sorry im still new in this programming..sorry for my english
Here is a revised version of your function to check if a name appears twice in any string in the array
function alreadyInList(list, toBeAdded) {
// return true or false
var delims = ",",
tokens = list.split(delims),
found = false;
var end = tokens.forEach(function (value) {
if (value.indexOf(toBeAdded) !== -1 && found == false) {
found = true;
alert('It\'s been found!');
// Do something
return true;
}
return false;
});
if (found != true) {
alert('Not in the list');
return false;
} else {
return false;
}
}
alreadyInList('marry,joe,gerry', 'marry');
JSFiddle Demo
Additionally if its just one occurance in the list you need something simple without a function.
var str = "marry,joe,gerry",
key = "marry";
if ( str.indexOf(key) !== -1 ) {
// Its found! Do something
}
As Sasquatch pointed out above, the issue is the delimiter you are using for split. You want to split by a single comma ',' -- not by the three characters '(,)'.
The way your code is written, tokens only ever has a single value because the split delimiter is wrong. It is matching the entire string variable list to your toBeAdded string and returning false.

Why this replace doesn't work Javascript? [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 7 years ago.
I want to know why this procedure doesn't replace words
I have to do a procedure which reads a string and replace all word like this {{employee.Name}} into a value on the ticket's scope
var mySplitResult = Val.split(' ');
for (var i = 0; i < mySplitResult.length; i++) {
if (mySplitResult[i].match("{{") && mySplitResult[i].match(".")) {
var start = mySplitResult[i].lastIndexOf(".") + 1;
var end = mySplitResult[i].indexOf("}}");
var result = mySplitResult[i].substring(start, end);
for (var key in ticket.PNData) {
if (key == result) {
change.replace(mySplitResult[i], ticket.PNData[key]);
alert(change)
}
}
}
}
In JavaScript strings are immutable which means you must assign the result to a variable.
mySplitResult[i] = mychange.replace(mySplitResult[i], ticket.PNData[key]);

Alternative to eval [duplicate]

This question already has answers here:
Alternative to eval() javascript [duplicate]
(6 answers)
Closed 9 years ago.
I am making some common function where in I pass the array, name of field from array, value of field in array and return field name to return value as below
function arrayFilter(_array, findField, value, returnField) {
var temp = "_array[i]." + findField;
var retValue = "";
for (var i = 0; i < _array.length; i++) {
if (eval(temp) == value) {
return eval("_array[i]." + returnField);
}
}
}
But when I read on Internet I found that eval is not good, it can have string injection attack.
So somebody help on above.
Instead of:
return eval("_array[i]." + returnField);
Try:
return _array[i][returnField];
And also read this article.
You can use the square bracket notation for accessing properties when the value of your key is unknown.
function arrayFilter(_array, findField, value, returnField) {
var temp = _array[i][findField];
var retValue = "";
for (var i = 0; i < _array.length; i++) {
if (temp == value) {
return _array[i][returnField];
}
}
}

how to textract &client= from url? [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 years ago.
If my url is http://link-ads.blogspot.com/?url=http://could-be-any-url.com&name=123456789101112 using purely javascript how would I extract &client= so it would extract 123456789101112 and set it as var clientid = 123456789101112;
var clientid = (window.location.search.match(/[?&;]name=(\d+)/) || [])[1];
If it can contain more than numbers, use something like...
var clientid = (window.location.search.match(/[?&;]name=([^&;]+)/) || [])[1];
If the param could not be found, it will return undefined.
If you need to do this more often, you'd be better off with a generic solution.
try this:
var url = "http://link-ads.blogspot.com/?url=http://could-be-any-url.com&name=123456789101112"
var name = url.substring(url.indexOf('&name='), url.length)
If you don't want to user regular expression like the other answer
For a more generic/reusable solution, you can use something like:
getParameter = function(paramName, url) {
if (! paramName) {
return null;
}
if (! url) {
url = window.location.href;
}
if (url.indexOf('?') == -1) {
return null;
}
url = url.substring(url.indexOf('?') + 1);
var params = url.split('&');
for (var index = 0; index < params.length; index++) {
var nameValue = params[index].split('=');
if (nameValue.length == 2 && nameValue[0] == paramName) {
return nameValue[1];
}
}
return null;
};
...then just call getParameter('client');.
Example here: http://jsfiddle.net/L7hbT/3/
Not as succinct as #alex, but you could do this
var a = 'http://link-ads.blogspot.com/?url=http://could-be-any-url.com&name=123456789101112';
var b = a.indexOf('name=');
var clientId = a.substring(b + 5);
alert(clientId);
Example: http://jsfiddle.net/jasongennaro/ubJe3/

Categories