I have a few comma-separated URLs as shown below.
https://drive.google.com/open?id=17kTY2b3XvERC4wqZnLt7sVwMe8ZoDZUD, https://drive.google.com/open?id=1En1tNNLEgz5JiIk2GJnjNb_bhk23YJb2, https://drive.google.com/open?id=2En1tNNLEgz5JiIk3GJnjNb_bhk23YJb2
I need to get just the IDs (Example: 17kTY2b3XvERC4wqZnLt7sVwMe8ZoDZUD) from it in an array.
I'm a rookie coder and would appreciate it if someone can help me with the code.
Use the URL parsing library built-in to the browser. Don't attempt to use regular expressions to pick apart the URL because you don't have to (and you might end up getting it wrong).
var u = new URL("https://drive.google.com/open?id=2En1tNNLEgz5JiIk3GJnjNb_bhk23YJb2");
console.log(u.searchParams.get('id'));
> "2En1tNNLEgz5JiIk3GJnjNb_bhk23YJb2"
You could use string.split("?id=") and get the second element from the array returned (element 0 for everything to the left, 1 for the right)
E.G:
<script>
var myArray = ["https://drive.google.com/open?id=17kTY2b3XvERC4wqZnLt7sVwMe8ZoDZUD",
"https://drive.google.com/open?id=1En1tNNLEgz5JiIk2GJnjNb_bhk23YJb2",
"https://drive.google.com/open?id=2En1tNNLEgz5JiIk3GJnjNb_bhk23YJb2"];
for(var i=0; i<myArray.length; i++)
{
var result = myArray[i].split("?id=")[1];
console.log(result);
}
</script>
Related
I would love some advice. I'm trying to get some text out of a long string. The string is here: http://espn.go.com/nba/bottomline/scores
I have the script that makes an HTTP request to get all this text, but need help only taking certian things from this long string.
I would like to grab this text from the long string:
Cleveland%20114%20%20%20LA%20Clippers%2090%20(FINAL)
Indiana%20at%20Atlanta%20(6:00%20PM%20ET)
Utah%20at%20Sacramento%20(6:00%20PM%20ET)
Milwaukee%20at%20Brooklyn%20(8:00%20PM%20ET)
New%20York%20at%20LA%20Lakers%20(9:30%20PM%20ET)
I'm not sure the best way to go about it.. Should I try to grab the text between each nba_s_left1= and &. If so, how would I go about that?
It seems that the whole long string is one big query string. So you can parse it with this js function:
function parseQuery(qstr) {
var query = {};
var a = qstr.substr(1).split('&');
for (var i = 0; i < a.length; i++) {
var b = a[i].split('=');
query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
}
return query;
}
query = parseQuery(longString);
And then you can just get the part, that interests you, by calling query["nba_s_left1"]
Basically, I want to be able to call a function on some html string and get back an array of the start and end indices of the occurrences. It would look like this in the console:
var html = "<b>Hello</b> <mark>World</mark>";
> getIndices(html, "Hello\u00A0World");
< [[3, 29]]
The end goal of doing this is to be able to wrap the html with some tags given a string to search in the document, much like the ctrl+f functionality of most browsers do.
I wrote the code snippet below but its performance is horrible, specially on long webpages when calling it on the entire body's inner html. This code can definitely be optimized by doing a binary search as opposed to brute force and doing some other things a bit differently but I'm having trouble implementing that. Thoughts on this?
function getIndices(html, searchTerm){
var i = 0,
indices = [];
while(html.slice(i).replace(/<[^>]*>/g, '').indexOf(searchTerm) !== -1){
i = html.indexOf(searchTerm[0], i);
if(html.slice(i).replace(/<[^>]*>/g, '').indexOf(searchTerm) === 0){
indices.push(i);
}
i++;
}
return indices;
}
Thanks!
Create a treewalker and check which nodes contain the search string
I'm trying to write a Javascript function to get the query string of the browser and allow a new key/value to be passed to the function. If the key exists, I need to replace the value. Since I've spent the last 3.5 hours on this, I haven't yet gotten around to the replacing part.
So far, I'm using the answer here: How to get the query string by javascript? to get the query string. However, it doesn't appear to work... The URL I was testing with was: http://www.site.com/poo?drwho=tombaker&companion=k9
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
assoc[decode(key[0])] = decode(key[1]);
}
if(assoc["dr"] === undefined ) {
// not found. todo: replace
}
I'd really appricate any help! Is there any simpler way of doing this using JQuery?
Copy and pasted your code here: http://jsfiddle.net/6KcWh/5/, and added a call to JSON.stringify() to examine the contents of assoc. It turns out assoc is not undefined. But, of course assoc.dr is undefined, because there is no querystring argument of dr. There is a querystring argument of drwho. It looks like you were looking for the wrong querystring argument.
You appear to be misusing for...in.
Try converting your for loop to a standard for (i = 0 ; i < keyValues.length; i++) and check out some other answers about what for...in is used for in JavaScript.
A jQuery selector $(".thumb_up") returns a collection of forms like this:
[<form id="like_post_78" ...</form> <form id="like_post_79"> ... </form>]
Ultimately I want to generate a string consisting of the numerical ending portion of the form ids.
"78,79"
What's the most efficient way of getting this?
The easiest way is probably:
var form_ids = $('form').map(function(){return this.id.replace(/[a-z_]/gi,'');}).get().join(', ');
console.log(form_ids); // or alert() or whatever...
JS Fiddle demo.
I've just updated the regex portion of the above, from /[a-z_]/gi to /\D/g (which basically greedily (g) replaces any non-digit characters (\D) with 'nothing'), to give the following code:
var form_ids = $('form').map(function(){return this.id.replace(/\D/g,'');}).get().join(', ');
console.log(form_ids);
JS Fiddle demo.
Edited after thinking on #James Hill's accurate observation (below) that easiest != most efficient:
keep in mind that the OP asks for the most efficient method, not the easiest.
Therefore, using plain JavaScript (which should, to the best of my knowledge, be available cross-browser):
var form_ids = [];
var forms = document.getElementsByTagName('form');
for (var i=0; i<forms.length; i++){
form_ids.push(forms[i].id.replace(/\D/g,''));
}
console.log(form_ids.join(', '));
JS Fiddle demo.
With a comparison of the two over at JS Perf, showing that JavaScript tends to be the faster (which implies it's more efficient, presumably because it's running native JavaScript/ECMAscript, rather than abstracted code that then calls native JavaScript/ECMAscript...)).
References:
map().
get().
join() at the MDN.
replace() at the MDN.
Option 1
Use jQuery's each() function in combination with the class selector:
var aryIDs = [];
$(".thumb_up").each(function(){
//Add ID to the array while stripping off all non-numeric data using RegEx
aryIDs.push(this.id.replace(/\D/g, ""));
});
//Get the ids
var csvIDs = aryIDs.toString();
Option 2
Grab the elements with jQuery and then use a plain old for loop:
var aryIDs = [];
var divs = $(".thumb_up");
for(var i= 0; i < divs.length; i++)
{
aryIDs.push(divs[i].id.replace(/\D/g, ""));
}
var csvIDs = aryIDs.toString();
Here's a working jsFiddle of the latter example.
Performance
As for performance, the for loop should be faster every time. Check out a simple jsPerf I created to compare the performance of .each(), .map(), and a standard for loop.
var str = "";
$(".thumb_up").each(function(){
var id = $(this).attr('id').split('like_post_');
str += id[1] + ',';
});
You'll end up with an extra "," at the end, but you can get to what you want with this basic example.
Just for the record, there is a document.forms collection that is every form in the document, so getting an array of all form ids is as simple as:
var ids = [];
var forms = document.forms;
for (var i = forms.length; i;) {
ids[--i] = forms[i].id;
}
If your definition of "efficiency" means fastest, the above should run rings about any of the jQuery answers (it does). If you only want forms with a particular class, it wouldn't be hard to filter them out with test of the form's className property in the loop.
In JS, I'm having trouble working out how to split a string coming from an AJAX call.
This is what I have so far:
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
feedUpdateResponse = xmlhttp.responseText;
/////...split script.../////
}
}
xmlhttp.open("GET","https://myDomain.com/myScript.aspx",true);
xmlhttp.send();
Where you have /////...split script...///// in my script above, I need to add a little function that splits the string returned from my AJAX call.
The string simply contains names of DIVs, like this:
feedUpdateResponse = "div1/div2/div3/div4"
I would like to first split the string by its slashes (/) and run a loop through the different values and do stuff to those elements on my page.
To give an idea of what I need to achieve, I have given this example which is a mix of ASP & JS - it's the only way I can possibly describe it (and show that I've had an attempt) :)
MyArray = Split(feedUpdateResponse,"/")
For Each X In MyArray
documentGetElementById('updateAvailable_'+x).style.visibility="visible";
Next
On my page I have an ASP script that produces jquery carousels, all contained by separate DIVs. The DIVs are named DIV1, DIV2 etc. Inside DIV1, for example, is a text element called updateAvailable_div1 which will alert the user "There are new photos available for this feed, please click the refresh button".
Could somebody please explain to me how I can change my example above to work in JS? Just need to split the string into an array and loop through the split values...
You can use .split() to split a string on a specified character with the results returned as an array. So then it's just a matter of looping through the array:
// given your existing variable
// feedUpdateResponse = "div1/div2/div3/div4" as set in the
// code in the question, add this:
var a = feedUpdateResponse.split("/"),
i;
for (i = 0; i < a.length; i++) {
document.getElementById("updateAvailable_" + a[i]).style.visibility
= "visible";
}
Get your array via string.split("/"). Iterate your array using your method of choice. I prefer Array.forEach():
feedUpdateResponse.split("/").forEach(function (item) {
document.getElementById(item).style.visibility = "visible";
});
See the compatibility notes for using .forEach() in older browsers.
As an alternative:
for(element of feedUpdateResponse.split("/")){
do_your_thing();
}
Using for..in will end up giving you the indices on the array (keys), while for..on will give you the elements of the array (values).
You can also do:
for ([index, element] of Object.entries(feedUpdateResponse.split("/"))) {
do_your_thing();
}
In the event that you need the index.
The disadvantage is it not being compatible with IE, but for personal projects or a quick automation script it usually does me plenty fine.
Try this code:
var a = feedUpdateResponse.split("/");
for (i in a) {
document.getElementById("updateAvailable_" + a[i]).style.visibility
= "visible";
}
var feedUpdateResponse = "div1/div2/div3/div4";
var feedUpdateSplit = feedUpdateResponse.split("/");
for (var x = 0; x < feedUpdateSplit.length; x++) {
document.getElementById("updateAvailable_" + feedUpdateSplit[x]).style.visibility = "visible";
}