javascript only get last number in chain - javascript

I have a bunch of numbers coming back from an api. It looks like this
1,2,3,4,5,6
Now i'm only wanting the last digit to be displayed rather than all of them.
How would i go about doing this? I need to add .slice on the end but im not sure what to put in the ()
Thanks
Sam

try this
.slice(-1)[0]
or
.slice(-1).pop()

var str = "1,2,3,4,5,6";
var _lastNum = str.slice(-1*(str.length - str.lastIndexOf(",")-1)); // Will return 6;

By far, voids answer seems to be the most comfortable and shortest one. But if you attempt to use at least one of the numbers at any time again, you may use something like this:
var str = "1,2,3,4,5,6"
str = str.split(',')
var lastNum = str[str.length-1]
As RobG wrote, you could also do
var lastNum = str.pop()

Related

JavaScript string .replace for URL

I scrape sites for a database with a chrome extension,
need assitance with a JavaScript Clean up function
e.g
https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p
my target output is:
_60789694386.html
everything past .html needs to be removed, but since it is diffrent in each URL - i'm lost
the output is in a .csv file, in which i run a JavaScript to clean up the data.
this.values[8] = this.values[8].replace("https://www.alibaba.com/product-detail/","");
this.values[8] is how i target the column in the script. (Column 8 holds the URL)
Well, you can use split.
var final = this.values[8].split('.html')[0]
split gives you an array of items split by a string, in your case'.html', then you take the first one.
Consider using substr
this.values[8] = this.values[8].substr(0,this.values[8].indexOf('?'))
You can use split method to divide text from ? as in example.
var link = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p"
var result = link.split('?')[0].replace("https://www.alibaba.com/product-detail/","");
console.log(result);
Not sure i understood your problem, but try this
var s = 'https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p'
s = s.substring(0, s.indexOf('?'));
console.log( s );
For when you don't care about readability...
this.values[8] = new URL(this.values[8]).pathname.split("/").pop().replace(".html","");
Alternate, without using split
var link = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p"
var result = link.replace('https://www.alibaba.com/product-detail/', '').replace(/\?.*$/, '');
console.log(result);
You can use the regex to get it done. As of my knowledge you do something like:
var v = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p"
result = (v.match(/[^\/]+$/)[0]);
result = result.substring(0,result.indexOf('?'));
console.log(result); // will return _60789694386.html

Javascript: given an array of variables, function to remove characters and output another array

so I am still learning Javascript, so I know this is a basic questions, and I'd really like to learn what I'm missing. I have an array of variables, and I need a function that removes special characters, and returns the result as an array.
Here's my code:
var myArray = [what_hap, desc_injury];
function ds (string) {
string.replace(/[\\]/g, ' ')
string.replace(/[\"]/g, ' ')
string.replace(/[\/]/g, '-')
string.replace(/[\b]/g, ' ')
string.replace(/[\f]/g, ' ')
string.replace(/[\n]/g, ',')
string.replace(/[\r]/g, ' ')
string.replace(/[\t]/g, ' ');
return string;
}
ds (myArray);
I know that's not going to work, so I'm just trying to learn the simplest and cleanest way to output:
[whatHap: TEXTw/oSpecialCharacters, descInj: TEXTw/oSpecialCharacters]
Anyone willing to guide a noobie? Thanks! :)
The comments on the question are correct, you need to specify what you are asking a little better but I will try and give you some guidance from what I assume about your intended result.
One important thing to note which would fix the function you already have is that string.replace() will not change the string itself, it returns a new string with the replacements as you can see in the documentation. to do many replacements you need to do string = string.replace('a', '-')
On to a solution for the whole array. There are a couple ways to process an array in javascript: for loop, Array.forEach(), or Array.map(). I urge you to read the documentation of each and look up examples on your own to understand each and where they are most useful.
Since you want to replace everything in your array I suggest using .map()
or .foreach() since these will loop through the whole array for you without you having to keep track of the index yourself. Below are examples of using each to implement what I think you are going for.
Map
function removeSpecial(str) {
// replace all these character with ' '
// \ " \b \f \r \t
str = str.replace(/[\\"\b\f\r\t]/g, ' ');
// replace / with -
str = str.replace(/\//g, '-');
// replace \n with ,
str = str.replace(/\n/g, ',');
return str;
}
let myArray = ["string\\other", "test/path"];
let withoutSpecial = myArray.map(removeSpecial); // ["string other", "test-path"]
forEach
function removeSpecial(myArray) {
let withoutSpecial = [];
myArray.forEach(function(str) {
str = str.replace(/[\\"\b\f\r\t]/g, ' ');
// replace / with -
str = str.replace(/\//g, '-');
// replace \n with ,
str = str.replace(/\n/g, ',');
withoutSpecial.push(str)
});
return withoutSpecial;
}
let myArray = ["string\\other", "test/path"];
let withoutSpecial = removeSpecial(myArray); // ["string other", "test-path"]
The internalals of each function's can be whatever replacements you need it to be or you could replace them with the function you already have. Map is stronger in this situation because it will replace the values in the array, it's used to map the existing values to new corresponding values one to one for every element. On the other hand the forEach solution requires you to create and add elements to a new array, this is better for when you need to do something outside the array itself for every element in the array.
PS. you should check out https://regex101.com/ for help building regular expressions if you want a more complex replacements but you dont really need them for this situation
I realize that the way I wrote my goal isn't exactly clear. I think what I should have said was that given several text strings, I want to strip out some specific characters (quotes, for example), and then output each of those into an array that can be accessed. I have read about arrays, it's just been my experience in learning JS that reading code and actually doing code are two very different things.
So I appreciate the references to documentation, what I really needed to see was a real life example code.
I ended up finding a solution that works:
function escapeData(data) {
return data
.replace(/\r/g, "");
}
var result = {};
result.what_hap_escaped = escapeData($what_hap);
result.desc_injury_escaped = escapeData($desc_injury);
result;
I appreciate everyone's time, and hope I didn't annoy you guys too much with my poorly constructed question :)

Why do I get undefined here?

function myFunc() {
var word = document.getElementById("Text1").value;
var num = parseInt(document.getElementById("Text2").value);
var numstr = num.split(",");
var wordstr = word.split("");
for (i = 0; i < word.length; i++) {
}
document.getElementById("myDiv").innerHTML += (wordstr[(numstr[i])-1]);
}
did I parseInt incorrectly? I've tried toString(), with ParseInt it doesn't do anything and without it I get 'undefined'
The parseInt() function parses a string and returns an integer.
You check your input with id "Text2" and show your HTML here to clearify the issue.
Without knowing more about your problem, it looks like you are misunderstanding how parseInt() works. Despite the misleading name, it will read your string character by character, attempting to create an integer. It will stop as soon as it finds a character that can't be part of an integer.
If you pass it "1,2,3,4" then it will read the 2 fine, but as a comma cannot be parsed as part of an integer, it will return the number 2. It doesn't make sense to call split on a number.
As others have said, you really need to give us more details for us to be able to help, but I suspect a large part of the problem is not understanding what some of these functions do.
Maybe you could explain what you're trying to achieve, then we can help you get there. Right now, your code isn't clear enough without extra information.

What is a better way to remove element from a string and join it?

Is there a better way to do this using chaining?
var url = "www.mycompany.com/sites/demo/t1"
var x = url.split('/');
console.log(x);
var y = x.pop();
console.log(y,x);
var z = x.join("/");
console.log(z);
I tried something like but wouldn't work since pop just returns the last value and not the rest:
parentUrl = self.attr('Url').split("/").pop().join("/");
You could certainly do this with a regex replacement:
var url = "www.mycompany.com/sites/demo/t1";
var z = url.replace(/\/[^\/]+$/, '');
console.log(z);
This Regex should do the trick:
var url = "www.mycompany.com/sites/demo/t1"
console.log(url.match(/^(.+)\/(.+)/));
I solved it using lodash. The _.initial() does exactly what I'm looking for.
var url = "www.mycompany.com/sites/demo/t1";
var x = _.initial(url.split("/")).join('/');
console.log(x);
The regex solutions worked as well. However, I don't know how to read regex yet so I didn't feel comfortable using something I didn't really understand. But they work so thanks.
EDIT: My project already has the lodash library so I'm not adding a library just for this :)

Convert List to Structure Using Javascript or JQuery

I've apologize if this is a trivial task, and I've also been googling and searching high and low for some solution I can get my head around but so far no dice. So anyways....
I have this:
var myList = "key1,value1,key2,value2"
And I want to populate a struct with this string so I can reference it like this:
alert(myList.key1) // displays value1
Thoughts? There's probably some way to do this with JQuery's .each() perhaps? I'm seriously lost either way! Maybe just because it's really late and I've been stumbling through familiarizing myself with JS and JQuery again after a long hiatus. Any help is appreciated!
Assuming you never have commas in the values, you could start by using split:
var parts = myList.split(",");// ["key1", "value1", ...]
From there you can just use a simple loop:
var obj = {};
for (var i = 0; i < parts.length; i+=2) obj[parts[i]] = parts[i + 1];
As this answer points out, you can also write the loop like this:
var obj = {};
while (parts.length) obj[parts.shift()] = parts.shift();
This is a neat way to write this, but behaves differently: after this loop, parts will be empty.
String.replace method is your first choice when it comes to string parsing tasks
var myList = "key1,value1,key2,value2"
var result = {}
myList.replace(/(\w+),(\w+)/g, function($0, $1, $2) {
result[$1] = $2
})

Categories