i have long csv with data... like 1,2,3,........,120
i want to check if it is last one. but how to do it with javascript?
here iam splitting all csv and getting each one separate.
var movieSRC = CSV;
if (movieSRC.indexOf(',') > -1) {
movieSRC = movieSRC.split(',');
for (var i = 0; i < movieSRC.length; i++) {
***//need to check if it is a last one!!!***
movies.push(movieSRC[i]);
}
//Using split() method
var arr = movieSRC.split(','); //give you an array
var element = arr[arr.length-1]; //get the last element of array
//Ussing substring() and lastIndexOf()
var element = movieSRC.substring(movieSRC.lastIndexOf(',')+1);
As suggested in the comment, you could also use Array.pop() method, however it will remove the element from the array:
var element = movieSRC.split(',').pop();
Related
I'm new to JavaScript and I'm trying to figure out how-to loop through JSON and print each selected value in HTML. My solution below does everything I want except print "all" rows of the JSON data. It only prints the last one. I've been researching on StackOverflow and elsewhere, but I'm not finding the solution. Sorry if this is a redundant question and thank you for your help!
//Fetch JSON from URL
//https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('https://s.codetasty.com/toddbenrud/sandBoxToddBenrud/example/songData.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
var songData = (JSON.stringify(myJson));
//https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript
var index;
var obj = JSON.parse(songData);
for (index = 0; index < obj.length; ++index) {
var student_name = obj[index]['name'];
var student_email = obj[index]['email'];
var song_name = obj[index]['song'];
var song_url = obj[index]['url'];
document.getElementById("studentName").innerHTML = '<br>'+student_name;
document.getElementById("studentEmail").innerHTML = '<br>'+student_email;
document.getElementById("songTitle").innerHTML = '<br>'+song_name;
document.getElementById("songURL").innerHTML = '<br>'+song_url;
}
});
Inside your for loop you are reassigning your elements' content in every Iteration. It means that you fill your elements with the First item of the Array on the First time you run the for, but the Second time you run It, you replace the elements' content with the Second item of the Array. So you get only the Last Item Data.
To solve this problema, you should "increment" your element's content on each Iteration, instead of replace it. To achieve that, you replace the Lines like
document.getElementById("studentName").innerHTML = '<br>'+student_name;
With
document.getElementById("studentName").innerHTML += '<br>'+student_name;
The += operator does a concatenation on strings
Becasue you set string for elements, don't add string.
Replace from:
document.getElementById("studentName").innerHTML = '<br>'+student_name;
document.getElementById("studentEmail").innerHTML = '<br>'+student_email;
document.getElementById("songTitle").innerHTML = '<br>'+song_name;
document.getElementById("songURL").innerHTML = '<br>'+song_url;
To:
document.getElementById("studentName").innerHTML += '<br>'+student_name;
document.getElementById("studentEmail").innerHTML += '<br>'+student_email;
document.getElementById("songTitle").innerHTML += '<br>'+song_name;
document.getElementById("songURL").innerHTML += '<br>'+song_url;
I have been stuck on this as I am not the best with mixing arrays + string matches.
What I would like to do is return the index number within an array based on a partial match from a string. Full use case; check if text exists in a URL based off values within an array - and return the index of array position.
Don't mind JS or jQuery but whichever might be most efficient is fine (or works).
Current attempt:
Example URL = www.site.com/something/car/123
Another Example URL might be www.site.com/something/somethingelse/banana/
(location of snippet to match is not always in the same path location)
var pageURL = location.href;
var urlArray = ['/car/','/boat/','/apple/','/banana/'];
function contains(urlArray, value) {
var i = urlArray.length;
while (i--) { if (urlArray[i].indexOf(pageURL)) console.log(i)} console.log('Not Found');}
alternate Using jQuery (not sure where to use indexOf or another jQuery alternative (.search / .contains)):
urlArray.each(function(){
$.each(this, function(index) { } ) });
Expected output for first URL would be 0, second example URL would be 3.
Help is much appreciated!
You can iterate over the array with findIndex() to get the index if the includes() the string.
This will go through the urlArray and return the index of the first match (and -1 if a match isn't found).
let URL1 = "www.site.com/something/car/123"
let URL2 = "www.site.com/something/somethingelse/banana/"
let urlArray = ['/car/','/boat/','/apple/','/banana/'];
let index1 = urlArray.findIndex(str => URL1.includes(str))
let index2 = urlArray.findIndex(str => URL2.includes(str))
console.log(index1, index2)
You can also use a forEach() loop on the urlArray to get each word from the array and check if it exist in url or not.
var url = 'www.site.com/car/somethingelse/banana/';
var urlArray = ['/car/', '/boat/', '/apple/', '/banana/'];
urlArray.forEach(function(word){
//if word exist in url
var wordIndex = url.indexOf(word);
if(wordIndex !== -1){
console.log(wordIndex);
}
});
NOTE includes() do not work in IE browser and older versions thus to make it work on all browsers the recommended way is to avoid arrow functions with includes() and instead use plain function with indexOf()
To return the array index:
var url = 'www.site.com/car/somethingelse/banana/';
var urlArray = ['/car/', '/boat/', '/apple/', '/banana/'];
urlArray.forEach(function(word, index){
//if word exist in url
if(url.indexOf(word) !== -1){
console.log(index);
}
});
for (var i = 0; i < urlArray.length; i++) {
if(pageURL .indexOf(urlArray[i])>-1){
console.log(pageURL.indexOf(urlArray[i])));
}
}
First post please go easy on me.
I have an array that looks something like this [BTC-LTC, BTC-DOGE, BTC-VTC] I am trying to change all the "-" with "_". But am having trouble with using the .replace() method. Here is my code.
var array = [BTC-LTC, BTC-DOGE, BTC-VTC];
var fixedArray = [];
for(var i=0; i <= array.length; i++){
var str = JSON.stringify(array[i]);
var res = str.replace("-","_");
fixedArray.push(res);
};
I tried without using the JSON.stringify but that didn't work either. I have also tried to first create var str = String(); this also did not work. Is it possible that the method .replace() is not available in google scripts?
In your example var array = [BTC-LTC, BTC-DOGE, BTC-VTC];
should be
var array = ["BTC-LTC", "BTC-DOGE", "BTC-VTC"];
However I gather from the comments that this is just a typo in your initial example.
var str = JSON.stringify(array[i]); is redundant. You can just do var str = array[i]; Since the value in the array is already a string, there's no need to turn it into one again - the "stringify" method expects to be given an object or array to work on.
However the main problem is that your for loop goes on one too many iterations. Arrays are zero-based, so you need to stop looping when the index is 1 less than the length of the array, not equal to it. e.g. if array.length is 10 then there are 10 indices, but they start at 0, so the indices are 0,1,2,3,4,5,6,7,8,9. If your loop goes on to equal to array.length, then on the last loop array[10] will be out of bounds, and it's only this last iteration which is giving you the undefined error.
var array = ["BTC-LTC", "BTC-DOGE", "BTC-VTC"];
var fixedArray = [];
for (var i = 0; i < array.length; i++) {
var str = array[i];
var res = str.replace("-","_");
fixedArray.push(res);
}
If I understood correctly, you're trying to edit strings, not variables, so you need quotes in your array, and a g in your replace in case you have multiple things to replace :
var array = ['BTC-LTC', 'BTC-DOGE', 'BTC-VTC'];
var fixedArray = [];
for(var i=0; i <= array.length; i++){
fixedArray.push(array[i].replace(/-/g, '_'));
};
code is working fine if we change as below:
var array = ['BTC-LTC', 'BTC-DOGE', 'BTC-VTC'];
How would I find a word (in this case a placeholder, e.g _ORGAN_) in an array and replace it with an element's value?
sql = new Array();
$('#system').change(function(){
filter = " topography_index = _ORGAN_";
sql.push(filter);
});
In this case I would want to replace _ORGAN_ with $('#organ_menu').val();
Try this:
// sql array
var sql = ['organ not found', '_ORGAN_ is here'];
var val_to_replace = '_ORGAN_';
var replace_with = 'heart'; // temp value - change it with $('#organ_menu').val()
$.each(sql, function (key, val) {
// search for value and replace it
sql[key] = val.replace(val_to_replace, replace_with);
})
console.log(sql)
JSFiddle: http://jsfiddle.net/d8sZT/
You can simply do by iterating the array and then assign the value to once it find its match.
for (i = 0; i < sql.length; i++) {
if (sql[i] === "_ORGAN_") {
sql[i] = $('#organ_menu').val();
}
}
example fiddle for better understanding.
You can simply iterate over the array and use replace on each element
var organValue = $('#organ_menu').val();
for (var i = 0; i < sql.length; i++) {
sql[i] = sql[i].replace("_ORGAN_", organValue);
}
var regExp = new RegExp(organ, 'g');
$.each(sql, function(index, value) {
sql[index] = value.replace(regExp, 'test');
})
I'd try something like this, using replace:
sql = new Array();
$('#system').change(function(){
filter = " topography_index = _ORGAN_".replace("_ORGAN_", $('#organ_menu').val(), "gi");
sql.push(filter);
});
You can do this:
First find the index of the item:
var index=sql.indexOf("_ORGAN_");
Then insert your new item at that index and remove the first one:
sql.splice(index,1,newitem);
splice
I'm trying to populate a <span></span> element on the page load with jQuery.
At the moment the value that gets populated into the span is just an integer count.
Here I have named my span userCount:
Users<span id = "userCount"></span>
I am trying to write the value of the span with no success.
$(document).ready(function () {
$.post("Dashboard/UsersGet", {}, function (dataset) {
var obj = jQuery.parseJSON(dataSet);
var table = obj.Table;
var countUsers;
for (var i = 0, len = table.length; i < len; i++) {
var array = table[i];
if (array.Active == 1) {
var name = array.Name;
}
countUsers = i;
}
userCount.innerHTML = countUsers.toString();
});
});
You don't have any usercount variable. Use $(selector) to build a jquery object on which you can call functions like html.
$('#userCount').html(countUsers);
Note also that
you don't need to convert your integer to a string manually.
if you don't break from the loop, countUsers will always be table.length-1.
you have a typo : dataSet instead of dataset. Javascript is case sensitive.
you don't need to parse the result of the request
you don't need to pass empty data : jQuery.post checks the type of the provided parameters
So, this is probably more what you need, supposing you do other things in the loop :
$.post("Dashboard/UsersGet", function (dataset) {
var table = dataset.Table;
var countUsers = table.length; // -1 ?
// for now, the following loop is useless
for (var i=0, i<table.length; i++) { // really no need to optimize away the table.length
var array = table[i];
if (array.Active == 1) { // I hope array isn't an array...
var name = array.Name; // why ? This serves to nothing
}
}
$('#userCount').html(countUsers);
});
Use .html()!
Users<span id = "userCount"></span>
Since you have assigned an id to the span, you can easily populate the span with the help of id and the function .html().
$("#userCount").html(5000);
Or in your case:
$("#userCount").html(countUsers.toString());
Change:
userCount.innerHTML = countUsers.toString();
to:
$("#userCount").html(countUsers.toString());
Instead of:
userCount.innerHTML = countUsers.toString();
use:
$('#userCount').html(countUsers.toString());
You could use
$('#userCount').text(countUsers);
to write data to span
The call back argument should be dataSet rather than dataset?