How to remove a null element in jquery? - javascript

I have an application in which i am storing values in localstorage. By default my first value is null due to which i am getting error to run the code so i want to remove the first element and continue the processes. can anyone please help me how to remove first element from list?
Piece of my code is below:
var str = localStorage.getItem("appidlist");
var mySplitResult = str.split(",");
for(var i = 0; i < mySplitResult.length; i++) {
if (.....) {
.
.
}
}
where str returns null,1,2,3,.....
I hope my question is clear can anybody help me.

This should also work:
var str = localStorage.getItem("appidlist");
var mySplitResult = str.split(",");
mySplitResult.splice(0, 1);

You can use .shift().
mySplitResult.shift()

Instead of uing the shift() function, I would suggest you to create a function that return a new clean array. This will solve even the case where there are more than one (and in any postion) null value.
You can use this solution

This should do the trick:
var str = localStorage.getItem("appidlist");
var mySplitResult = str.split(",").splice(1); // Remove the first item.
for(var i = 0; i < mySplitResult.length; i++) {
// Stuff
}

Related

Replacing text in an input box of a webpage (with defined ID)

I am trying to fill up all the input fields of a webpage (having input IDs ending with txtValue) which are filled with the word ‘dog’ to be replaced with the word ‘cat’.
I have tried this code, but it isn’t working. Kindly help me to solve this. Thank you in advance.
const ta = document.querySelectorAll("[id$='txtValue']");
const str = ta.value.replace("dog","cat");
ta.value = str
console.log(ta.value,"change to" ,str)
querySelectorAll returns an array which needs to be iterated over.The replace method returns the modified string without changing the original.So,the following should work.
ta.forEach(elem => elem.value = elem.value.replace("dog","cat"))
querySelectorAll() returns a list. So you need to iterate the list to set each value.
const ta = document.querySelectorAll("[id$='txtValue']");
for (let i = 0; i <= ta.length; i++){
const str = ta[i].value.replace("dog","cat");
ta[i].value = str
}
console.log("finished");
This code is the answer to the question.
const ta = document.querySelectorAll("[id$='txtValue']");
for (let i = 0; i <= ta.length; i++){
const str = ta[i].value.replace("dog","cat");
ta[i].value = str
}
console.log("finished");

Search For Text in Div

I'm trying to make a runnable console command through Chrome that searches for the word "takeID", and then grabs the content immediately after it between = and & from a div class.
What I have so far doesn't work because I'm very bad at JS so any help would be appreciated. Below is what I have so far:
var iframe=document.getElementsByClassName("activity activity-container-html5");
var searchValue = "takeID";
for(var i=0;i<iframe.length;i++){ if(iframe[i].innerHTML.indexOf(searchValue)>-1){}};
var subString = iframe.substring( iframe.lastIndexOf("=")+1, iframe.lastIndexOf("&"));
console.log(searchValue+"="+subString);
An example of the div class it would be searching would look like:
<div class="activity activity-container-html5" config="{example text;takeID=cd251erwera34a&more example text}">
There are two issues with the code. The first issue is the searchValue posts to the console as whatever is in between the takeID, and not the actual result from searching. The second issue is that the code to search between = and & doesn't work at all and I don't know why. What is wrong with the code?
I just want an output that would post to the log or a popup window saying:
takeID=cd251erwera34a
EDIT:
Something else I thought of was how would you be able to just parse the div and then search for what is in between "takeID=" and "&"? I tried this but I was getting the error "Uncaught TypeError: iframe.lastIndexOf is not a function".
var iframe=document.getElementsByClassName("activity activity-container-html5");
var subString = iframe.substring( iframe.lastIndexOf("takeId=") + 1, iframe.lastIndexOf("&") );
console.log(subString);
I looked this up and I see this is because what it is trying to process is not a string but I'm not sure why that is or how to fix it.
I don't know about you but the best would be to use json directly inside the html tag like this:
<div class="activity activity-container-html5" config="{'example':'text', 'takeID':'cd251erwera34a', 'other':''}">
Or use an array and check manually if the one you are checking is the one you want, like this:
function config(element, searchValue) {
if (element.hasAttribute('config')) {
var configData = JSON.parse(element.getAttribute('config'));
var res = "";
for (var i = 0; i < configData.length; i++) {
if (configData[i].includes(searchValue)) {
res = configData[i];
break;
}
}
return res;
}
}
el = document.getElementsByClassName('activity activity-container-html5');
for (var i = 0; i < el.length; i++) {
console.log(config(el[i], "takeID"));
}
<div class="activity activity-container-html5" config='["example=text", "takeID=cd251erwera34a", "othertext=here"]'>
The array-type (second example) is most likely to work better than the simple json one (first one).
I figured out what I needed to do. Below is working code:
var iframe=document.getElementsByClassName("activity activity-container-html5");
var div = "";
for(var i=0;i < iframe.length; i++){
div += (iframe[i].outerHTML);
}
var take = /takeID=([a-z0-9]*)&/;
var capture = div.match(take);
var matchID = capture[1];
console.log(matchID);
window.alert("takeID=" + matchID);

How to remove a part of all strings in an array in javascript?

I want split array value .
for example
gUser[1] = CAR.BENZ.CCLASS.1962
gUser[2] = CAR.PORSCHE.911.2001
I want get string only BENZ.CLASS.1962 and PORSCHE.911.2001
How to split array value on java script?
#update.
not always CAR string.
so, not use substring.
You can use map to access each string in array then use replace. Use a regex to match string before '.' and replace only the first match, like this:
var gUser = ['CAR.BENZ.CCLASS.1962', 'CAR.PORSCHE.911.2001'];
var gUserModified = gUser.map(function(v){
return v.replace(/[^\.]+\./, '');
});
console.log(gUserModified);
Split it with dot then slice it and join it with dot
var gUser =[];
gUser[1] = "CAR.BENZ.CCLASS.1962";
gUser[2] = "CAR.PORSCHE.911.2001";
console.log(gUser[1].split('.').slice(1).join('.'));
console.log(gUser[2].split('.').slice(1).join('.'));
From your question, it's not clear if the array is a string array
If it is a string array you can do:
ES6+: gUser.map((user)=>{return user.split("CAR.")[1]})
ES5: gUser.map(function(user){return user.split("CAR.")[1]});
The below code is not tested but should probably work, with maybe minor tweaks
var splitStr = ''
var correctCarArr = []
for(let i = 0; i < gUser.length; i++){
splitStr = gUser[i].split('.')
let temp = ''
for(let j = 1; j < splitStr.length; j++){
temp += splitStr[j]
}
correctCarArr.push(temp)
}
var gUser = [];
gUser[1] = "CAR.BENZ.CCLASS.1962";
var gu1 = gUser[1].split(".");
gu1.shift();
console.log(gu1.join("."));
So here is the way without using any regex by only using string and array methods.
const gUser = ['CAR.BENZ.CCLASS.1962', 'CAR.PORSCHE.911.2001', 'XYZAB.PORSCHE.YSA.2021']
for (let i = 0; i < gUser.length; i++) {
console.log('Required String: ', gUser[i].split('.').slice(1).join('.'));
}
What we do is, we split the string into parts where . is encountered.
gUser[0].split('.') returns ['CAR', 'BENZ', 'CCLASS', '1962']
Later when slice(1) is called, the zeroth element of array is chopped off and will return ['BENZ', 'CCLASS', '1962']
And finally using join('.'), we merge the array elements to a single string with a . between each element, which returns BENZ.CCLASS.1962
Hope this helps! :)
Its easier split then shift the array to remove the first item like this:
gUser = ["CAR.BENZ.CCLASS.1962"];
var benz = gUser[0].split(".");
benz.shift();
alert(benz.join('.'));
There are other options from shift like slice(1) but In terms of performance, shift is apparently faster https://jsperf.com/shift-pop-vs-slice/4
Something Like This
`for(let index = 0; index < gUser.length; index++) {
console.log(gUser[index].split('.').splice(0, 1).join('.'));
}`
I haven't tested it. Please check and let me know

Print data value of array

I have a array that has IDs in JavaScript:
["1649545","1649546","1649547"] etc.
And I want to print the values of this array in a URL, so something like this the foreach function of PHP does;
foreach
www.google.com/[valueofarray]
end
I know the solution could be very easy, but I just cannot manage to find it.
I made a fiddle and used a for loop this is without the use of jQuery but only javascript. I made an example array called myArray, I used .length so that javascript stops when he's been through all of the strings in the example array.
var myArray = ['12345', '123456', '1234567'];
for (var i = 0; i < myArray.length; i++) {
console.log('http://foo.com/' + myArray[i]);
// alert(myArray[i]);
}
See it work (and be sure to open your browsers console or use alert instead for viewing the output)
jsFiddle
var p='http:',a=["1649545","1649546","1649547"],u='www.google.com';for(i=0; i<a.length; ++i) console.log([p,'',u,a[i]].join('/'));
Try this:
var idArray = ["1649545","1649546","1649547"];
var url = "www.google.com/";
idArray.forEach(function(id){
console.log("http://" + url + id);
});
https://jsfiddle.net/tcmn2Lda/

I want to loop through an array and modify attributes

Here is my code
var input_buttons = ["#one","#two","#three"];
var substr = input_buttons.split(',');
for(var i=0; i< substr.length; i++)
{
substr.attr('value', '');
}
Why doesn't this work?
Your first problem is calling split(',') on an array. However, if you just want to set the values of all those to a blank string you can do:
$('#one,#two,#three').val('');
If you want to set different values you'd need to loop through:
$('#one,#two,#three').each(function() {
// this == the HTML node (not a jQuery element)
this.value = someValue; // someValue would set outside
};
You already have an array, there is nothing to split, this only works on strings. You'd also have to pass the ID to jQuery before you can cal attr. In this case val is even better.
var input_buttons = ["#one","#two","#three"];
for(var i=input_buttons.length; i--;) {
$(input_buttons[i]).val('');
}
But shorter would be using the multiple selector:
$('#one, #two, #three').val('');
or if you already have the array, create a string by joining the IDs:
$(input_buttons.join(',')).val('');
I'm wondering why you are calling:
var substr = input_buttons.split(',');
By the nature of your input_buttons, you already have an array. All you should have to do is:
var input_buttons = ["#one","#two","#three"];
for(var i=0; i< substr.length; i++)
{
$(input_buttons[i]).attr('value', '');
}
var input_buttons = ["#one","#two","#three"];
$.each(input_buttons, function(idx, value) {
$(value).val('');
});
Or even better and shorter:
$('#one, #two, #three').val('');
You could also give those elements a common class name and then use this:
$('.className').val('');
your array contains just the id but not the actual object
try this
var input_buttons = ["#one","#two","#three"];
for(var i=0; i< input_buttons.length; i++)
{
$(input_buttons[i]).removeAttr('value');
}
input_buttons is already an array - don't split it.
To use .attr you need it to be a jquery object, so call $(input_buttons[i]).attr
Try the following to remove an attribute:
var input_buttons = ["#one","#two","#three"];
for(var i=0; i< input_buttons.length; i++)
{
$(input_buttons[i]).removeAttr('value');
}
The reason your code does not work is in the overloading of jQuery functions. .attr('value', '') evaluates to .attr('value'), which returns the value of value as opposed to setting it. The reason is that '' evaluates to false.

Categories

Resources