How to get characters from second last index using indexof in javaScript? - javascript

var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var n = absoluteURL.lastIndexOf('/');
var result = absoluteURL.substring(n + 1);
//alert(result);
console.log(result);
Here I get the result like 'vikas-kohli' as I am using lastIndexOf.
Now if someone wants to get characters from second last index, or it may be 3rd last index, then how can I get this?
I hope I am able to explain my question well

Insteadof using lastIndexOf('/') use string split('/') method.
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var splittedStr = absoluteURL.split('/');
console.log(splittedStr);
Then get the required element from an array.
var res = splittedStr[splittedStr.length-n]; // n: 1,2,3..
cosnole.log(res);
DEMO
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var splittedStr = absoluteURL.split('/');
console.log(splittedStr[splittedStr.length-2]);

Sth like this?
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var n = 2 //second last
var arr = absoluteURL.split('/')
console.log(arr[arr.length-n])

Just split your URL with /:
var absoluteUrl = "http://stackoverflow.com/users/6262169/vikas-kohli";window.location.pathname;
var splitedUrl = absoluteUrl .split('/');
console.log(splitedUrl);
Then get the element you want in the array.

IndexOf or something like that may not what you need. You can use split instead.
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli";
var partNo = 3;
var parts = absoluteURL.split('/');
alert(parts[parts.length - partNo]);

A simple for loop would do the trick.
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var n = absoluteURL.indexOf('/');
absoluteURL = absoluteURL.substring(n+2); // Becasue there are two / first
for(i = 0; i < x ; i++) // x should be such that if it is 1, then only the last string will come, if 2, then the last two strings
{
n = absoluteURL.indexOf('/');
absoluteURL = absoluteURL.substring(n+1);
}

You can use .split() on the window.location.pathname:
var locPath = "users/6262169/vikas-kohli"; // window.location.pathname;
var arr = locPath.split('/');
arr.forEach(function(item){
console.log(item);
});
With specific indexes:
var locPath = "users/6262169/vikas-kohli"; // window.location.pathname;
var arr = locPath.split('/');
console.log('last::::',arr[arr.length-1]);
console.log('second last::::', arr[arr.length-2]);
Or subsequent pop() can give you last item of array:
var locPath = "users/6262169/vikas-kohli"; // window.location.pathname;
var arr = locPath.split('/');
console.log(JSON.stringify(arr, 0, 0), '<---last::::popped-->',arr.pop());
console.log(JSON.stringify(arr, 0, 0), '<-----second last::::popped--->', arr.pop());

We can add a function to do that ourselves.
Add below code snippet:
String.prototype.nIndexOf = function (char, index) {
if (index >= this.split(char).length)
return -1;
else
return this.split(char, index).join(char).length;
}
Then you can use this as following:
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var n1 = absoluteURL.nIndexOf('/', 4);
var n2 = absoluteURL.nIndexOf('/', 5);
var result = absoluteURL.substring(n1 + 1, n2);
alert(result);

Hi if u can get nth Index from user u can use this
var nthIndex = 2;
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
for (i = 0; i < nthIndex; i++) {
var n = absoluteURL.lastIndexOf('/');
absoluteURL = absoluteURL.substring(0,n);}
alert(absoluteURL);

Concatenate string from the index you want after splitting it with /
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli";
var n = 2; // set the index from where you want to get characters
var arr = absoluteURL.split('/');
var a = [];
for(var i=n,j=0; i>=0; i--,j++){
a[j] = arr[arr.length-i];
}
console.log(a.join('')); // you can join it with any character

This should work:
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var results = absoluteURL.split('/');
var result = results[results.length-2];
alert(result);

Related

add elements of two arrays - the best way

var a = "1:2:3:4";
var b = "0:1:5:2";
I want at the end:
var c = "1:3:8:6";
meaning, the numbers are summed by column.
my solution is:
var i, k;
var a_arr = a.split(':');
var b_arr = b.split(':');
for (i=0;i<a_arr.length;i++){
and here again another loop over b_arr
}
eeh ok, I dont have solution.. what is the cutest way to do this?
You could just map it and return the added values ?
var a = "1:2:3:4";
var b = "0:1:5:2";
var c = a.split(':').map(function(x, i) {
return (+x) + (+b.split(':')[i]);
}).join(':');
document.body.innerHTML = '<pre>' + c + '</pre>';
or splitting outside the map
var c = (function(y) {
return a.split(':').map(function(x, i) {
return (+x) + (+y[i]);
}).join(':')
})(b.split(':'));
Building on my comment, you can use i to index both the arrays:
var i, k;
var a_arr = a.split(':');
var b_arr = b.split(':');
var c_arr = [];
for (i=0;i<a_arr.length;i++){
c_arr.push(parseInt(a_arr[i], 10) + parseInt(b_arr[i], 10));
}
//And use join to get the final result
var c = c_arr.join(":");
You can use index i to add the simply use join()
var a = "1:2:3:4";
var b = "0:1:5:2";
var c = [];
var i, k;
var a_arr = a.split(':');
var b_arr = b.split(':');
for (i=0;i<a_arr.length;i++){
c[i] = parseInt(a_arr[i], 10) + parseInt(b_arr[i], 10); //Add using index
}
console.log(c.join(':')); //Use Join
http://jsfiddle.net/fLavfcjz/1/
Use .map() and don't forget parseInt() otherwise the numbers will considered as strings.
var a = "1:2:3:4";
var b = "0:1:5:2";
var arrayA = a.split(':');
var arrayB = b.split(':');
var combinedArr = arrayA.map(function (v, i) {
return parseInt(v,10) + parseInt(arrayB[i],10); // or return (+v) + (+arrayB[i]);
});
console.log(combinedArr.join(':')); //1:3:8:6
Try this
var a = "1:2:3:4";
var b = "0:1:5:2";
var a_arr = a.split(':');
var b_arr = b.split(':');
var c_arr = [];
for (i in a_arr) {
var to_add = 0;
if (b_arr[i] != undefined) to_add = b_arr[i];
c_arr[i] = a_arr[i] + to_add;
}
You don't need a second loop. The resulting array of the following snippet will have the length of the shorter input array.
var a = '1:2:3:4'
var b = '0:1:5:2'
var aArray = a.split(':')
var bArray = b.split(':')
var result = []
for (
var i = 0, aLength = aArray.length, bLength = bArray.length;
i < aLength && i < bLength;
i++
) {
result.push(Number(a[i]) + Number(b[i]))
}
result = result.join(':')
console.log(result)

Returning multiple index values from an array using Javascript

I have an array containing the individual letters of a word and i want to search the array to return the index values of certain letters. However, if the word contains more a letter more than once (such as 'tree') the programme only returns one index value.
This is a sample of the code:
var chosenWord = "tree";
var individualLetters = chosenWord.split('');
var isLetterThere = individualLetters.indexOf(e);
console.log(isLetterThere);
this code will return the number '2', as that is the first instance of the letter 'e'. How would i get it to return 2 and 3 in the integer format, so that i could use them to replace items in another array using the .splice function.
indexOf takes a second parameter, as the position where it should start searching from.
So my approach would be:
function findLetterPositions(text, letter) {
var positions = new Array(),
pos = -1;
while ((pos = text.indexOf(letter, pos + 1)) != -1) {
positions.push(pos);
}
return positions;
}
console.log(findLetterPositions("Some eerie eels in every ensemble.", "e"));
http://jsfiddle.net/h2s7hk1r/
You could write a function like this:
function indexesOf(myWord, myLetter)
{
var indexes = new Array();
for(var i = 0; i < myWord.length; i++)
{
if(myWord.charAt(i) == myLetter)
{
indexes.push(i);
}
}
return indexes;
}
console.log(indexesOf("tree", "e"));
Loop through it as here:
var chosenWord = "tree";
var specifiedLetter = "e";
var individualLetters = chosenWord.split('');
var matches = [];
for(i = 0;i<individualLetters.length;i++){
if(individualLetters[i] == specifiedLetter)
matches[matches.length] = i;
}
console.log(matches);
An alternative using string methods.
var str = "thisisasimpleinput";
var cpy = str;
var indexes = [];
var n = -1;
for (var i = cpy.indexOf('i'); i > -1; i = cpy.indexOf('i')) {
n += i;
n++;
indexes.push(n);
cpy = cpy.slice(++i);
}
alert(indexes.toString());
var getLetterIndexes = function(word, letter) {
var indexes = [];
word.split("").forEach(function(el, i) {
el === letter && indexes.push(i);
});
return indexes;
};
getLetterIndexes("tree", "e"); // [2, 3]

How to build an array from a string in javascript?

I am trying to grab some values out of a sting that looks like this:
W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748
I want to make an array of all the keys and another array of all the values i.e. [W1, URML, MH…] and [0.687268668116, 0.126432054521...]
I have this snippet that does the trick, but only for the first value:
var foo = str.substring(str.indexOf(":") + 1);
Use split().
Demo here: http://jsfiddle.net/y9JNU/
var keys = [];
var values = [];
str.split(', ').forEach(function(pair) {
pair = pair.split(':');
keys.push(pair[0]);
values.push(pair[1]);
});
Without forEach() (IE < 9):
var keys = [];
var values = [];
var pairs = str.split(', ');
for (var i = 0, n = pairs.length; i < n; i++) {
var pair = pairs[i].split(':');
keys.push(pair[0]);
values.push(pair[1]);
};
This will give you the keys and values arrays
var keys = str.match(/\w+(?=:)/g),
values = str.match(/[\d.]+(?=,|$)/g);
RegExp visuals
/\w+(?=:)/g
/[\d.]+(?=,|$)/g
And another solution without using regexp
var pairs = str.split(" "),
keys = pairs.map(function(e) { return e.split(":")[0]; }),
values = pairs.map(function(e) { return e.split(":")[1]; });
JSFiddle
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748";
var all = str.split(","),
arrayOne = [],
arrayTwo = [];
for (var i = 0; i < all.length; i++) {
arrayOne.push(all[i].split(':')[0]);
arrayTwo.push(all[i].split(':')[1]);
}
parse the string to an array
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275";
var tokens = str.split(",");
var values = tokens.map(function (d) {
var i = d.indexOf(":");
return +d.substr(i + 1);
});
var keys = tokens.map(function (d) {
var i = d.indexOf(":");
return d.substr(0, i);
});
console.log(values);
console.log(keys);
http://jsfiddle.net/mjTWX/1/ here is the demo

Change Array Formatting

How to change this Javascript array format:
var sample_data = ["af","16.63","al","11.58","dz","158.97"];
to this object format:
var sample_data = {"af":"16.63","al":"11.58","dz":"158.97"};
Could use Array.shift to do it too. No idea how it compares to other methods speed wise.
var sample_data = ["af","16.63","al","11.58","dz","158.97"]; // source
var data = sample_data.slice(); // clone the data
sample_data = {};
while (data.length > 1) {
sample_data[data.shift()] = data.shift() || null;
}
var d = {}; // a temporary object
for (var i = 0; i < sample_data.length; i += 2) {
// iterate over sample_data with a step width of 2
// and set the the data in the temp. object
d[sample_data[i]] = sample_data[i+1];
}
sample_data = d;
the code for it will look like this
var sample_data = ["af","16.63","al","11.58","dz","158.97"];
var tmp = sample_data;
sample_data = {};
for (var i = 0; i < tmp.length / 2; i++)
sample_data[tmp[i * 2]] = tmp[i * 2 + 1];
EDIT
Keep in mind.
var arr = []; // This is an array
var obj = {}; // This is an object! Not array.

Javascript - Split dynamic string getting values inside brackets

I have this as data input (it's dynamic so it can be 1 up to 5 brackets in the same string)
data["optionBase"] = {} //declaration
data["optionBase"]["option"] = {} //declaration
data["optionBase"]["option"][value] = {} //declaration
data["optionBase"]["option"][value]["detail"] = somethingHere
Each line comes as a string, not as an array or any other type of javascript object.
How can i get an array out of that string containing something like this:
Line 1:
result[0] = "optionBase"
Line 2:
result[0] = "optionBase"
result[1] = "option"
Line 3:
result[0] = "optionBase"
result[1] = "option"
result[2] = value
Line 4:
result[0] = "optionBase"
result[1] = "option"
result[2] = value
result[3] = "detail"
var s1 = 'data["optionBase"] = {} //declaration';
var s2 = 'data["optionBase"]["option"] = {} //declaration';
var s3 = 'data["optionBase"]["option"][value] = {} //declaration';
var s4 = 'data["optionBase"]["option"][value]["detail"] = somethingHere';
var a = [s1, s2, s3, s4];
var regex = /data\[([^\]]+)\](?:\[([^\]]+)\])?(?:\[([^\]]+)\])?(?:\[([^\]]+)\])?/;
for(var i = 0; i < 4; i++)
{
var result = a[i].match(regex);
//result[0] contains the whole matched string
for(var j = 0; j < 5; j++)
console.log(result[j]);
}
If you want to make it dynamic, you can extract the string and split around ][
var s = 'data["optionBase"]["option"][value]["detail"] = somethingHere';
var m = s.match(/data((?:\[[^\]]+\])+)/);
var substr = m[1].substring(1, m[1].length - 1);
var array = substr.split("][");
console.log(array);

Categories