JavaScript remove everything before a character for a URL array - javascript

I currently have a blog featuring content within a div.
I have the following script which returns all a href tags in a blog.
function (){
var tags = [];
var count = $(".blog-featured").children().length;
for(var i=0; i<count; i++){
tags.push($('.blog-featured').children().eq(i).find('a').attr('href'));
}
return tags;
}
This is returning an array of URLs like the following [undefined, www.test.com.au/product/url/60145675?product/computer, www.test.com.au/product/url/6014 8796/test/products]
I would like to manipulate this array to:
Remove any spaces which may have occurred (not sure why but the script returns URLs with spaces)
Remove anything before a '6' and anything after the the 8(or 9 if the space isn't removed_) character product number
Remove any undefined values.
So the final array looks something like [60145675,60148796].

just split the href and replace any spaces before pushing it into the array:
eg: www.test.com.au/product/url/6014 8796/test/products
var loc =location.href;
var locPortions=loc.split("/");//splits the href at each "/";
var num=locPortions[3].replace(/ /g,"");//gets the desired portion of the href and replaces any spaces with no character - removing the spaces;
tags.push(num);//gives 60148796 out of the original href;
or to put it into your original function:
EDIT - function below amended to check for "6" at start of the locPortions.
function (){
var tags = [];
var count = $(".blog-featured").children().length;
for(i=0; i<count; i++){
var loc = $('.blog-featured').children().eq(i).find('a').attr('href');
var locPortions=loc.split("/");
for (ii=0;ii<locPortions.length;ii++){
if(locPortions[ii].charAt(0)=="6")
{
var num=locPortions[ii].replace(/ /g,"");}
tags.push(num);
}
}
return tags;
}

Related

How to remove all characters before specific character in array data

I have a comma-separated string being pulled into my application from a web service, which lists a user's roles. What I need to do with this string is turn it into an array, so I can then process it for my end result. I've successfully converted the string to an array with jQuery, which is goal #1. Goal #2, which I don't know how to do, is take the newly created array, and remove all characters before any array item that contains '/', including '/'.
I created a simple work-in-progress JSFiddle: https://jsfiddle.net/2Lfo4966/
The string I receive is the following:
ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC
ABCD/ in the string above can change, and may be XYZ, MNO, etc.
To convert to an array, I've done the following:
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
Using console.log, I get the following result:
["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"]
I'm now at the point where I need the code to look at each index of array, and if / exists, remove all characters before / including /.
I've searched for a solution, but the JS solutions I've found are for removing characters after a particular character, and are not quite what I need to get this done.
You can use a single for loop to go through the array, then split() the values by / and retrieve the last value of that resulting array using pop(). Try this:
for (var i = 0; i < currentUserRole.length; i++) {
var data = currentUserRole[i].split('/');
currentUserRole[i] = data.pop();
}
Example fiddle
The benefit of using pop() over an explicit index, eg [1], is that this code won't break if there are no or multiple slashes within the string.
You could go one step further and make this more succinct by using map():
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',').map(function(user) {
return user.split('/').pop();
});
console.log(currentUserRole);
You can loop through the array and perform this string replace:
currentUserRole.forEach(function (role) {
role = role.replace(/(.*\/)/g, '');
});
$(document).ready(function(){
var A=['ABCD','ABCD/Admin','ABCD/DataManagement','ABCD/XYZTeam','ABCD/DriverUsers','ABCD/RISC'];
$.each(A,function(i,v){
if(v.indexOf('/')){
var e=v.split('/');
A[i]=e[e.length-1];
}
})
console.log(A);
});
You could replace the unwanted parts.
var array = ["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"];
array = array.map(function (a) {
return a.replace(/^.*\//, '');
});
console.log(array);
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(i=0;i<currentUserRole.length;i++ ){
result = currentUserRole[i].split('/');
if(result[1]){
console.log(result[1]+'-'+i);
}
else{
console.log(result[0]+'-'+i);
}
}
In console, you will get required result and array index
I would do like this;
var iur = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC',
arr = iur.split(",").map(s => s.split("/").pop());
console.log(arr);
You can use the split method as you all ready know string split method and then use the pop method that will remove the last index of the array and return the value remove pop method
var importUserRole = ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++;){
var data = currentUserRole[x].split('/');
currentUserRole[x] = data.pop();
}
Here is a long way
You can iterate the array as you have done then check if includes the caracter '/' you will take the indexOf and substact the string after the '/'
substring method in javaScript
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++){
if(currentUserRole[x].includes('/')){
var lastIndex = currentUserRole[x].indexOf('/');
currentUserRole[x] = currentUserRole[x].substr(lastIndex+1);
}
}

how to split the textarea into parts in javascript

I am trying to open the 5 urls inputted by the user in the textarea
But the array is not taking the url separately instead taking them altogether:
function loadUrls()
{
var myurl=new Array();
for(var i=0;i<5;i++)
{
myurl[i] = document.getElementById("urls").value.split('\n');
window.open(myurl[i]);
}
}
You only should need to split the text contents once. Then iterate over each item in that array. I think what you want is:
function loadUrls() {
var myurls = document.getElementById("urls").value.split('\n');
for(var i=0; i<myurls.length; i++) {
window.open(myurls[i]);
}
}
Here's a working example:
var input = document.getElementById('urls');
var button = document.getElementById('open');
button.addEventListener('click', function() {
var urls = input.value.split('\n');
urls.forEach(function(url){
window.open(url);
});
});
<button id="open">Open URLs</button>
<textarea id="urls"></textarea>
Note that nowadays browsers take extra steps to block popups. Look into developer console for errors.
There are a couple issues I see with this.
You are declaring a new Array and then adding values by iterating through 5 times. What happens if they put in more than 5? Or less?
split returns a list already of the split items. So if you have a String: this is a test, and split it by spaces it will return: [this, is, a, test]. There for you don't need to split the items and manually add them to a new list.
I would suggest doing something like:
var myUrls = document.getElementById("urls").value.split('\n');
for (var i = 0; i < myUrls.length; i++) {
window.open(myUrls[i]);
}
However, as others suggested, why not just use multiple inputs instead of a text area? It would be easier to work with and probably be more user friendly.
Basically:
document.getElementById("urls").value.split('\n');
returns an array with each line from textarea. To get the first line you must declare [0] after split the function because it will return the first item in Array, as split will be returning an Array with each line from textarea.
document.getElementById("urls").value.split('\n')[0];
Your function could simplify to:
function loadUrls(){
var MyURL = document.getElementById("urls").value.split('\n');//The lines
for(var i=0, Length = MyURL.length; Length > i; i++)
//Loop from 0 to length of URLs
window.open(
MyURL[i]//Open URL in array by current loop position (i)
)
}
Example:
line_1...
line_2...
... To:
["line_1","line_2"]

How to get string in regular expression with space

This is my input as string
'controls: ["aa.bb.cc","dd.ee.ff"],elements: []'
I want to get the result of the data in the controls meaning :
"aa.bb.cc","dd.ee.ff"
I tried pattern
/.*(controls:.*).*/
but I didn't get all the result
I think my problem is becuase the new line
You can do it with regEx
var c = 'controls: ["aa.bb.cc", "dd.ee.ff"], elements: []';
var match = c.match(/("[a-z.]+")/g);
// or c.match(/([a-z][a-z][.][a-z][a-z][.][a-z][a-z])/);
// to strictly match letters . letters . letters
// or for a shorter match: c.match(/(\w+[.]\w+[.]\w+)/);
console.log(match); // an array of your values
EDIT:
if you only want to get the values in controls and not element, you can get the controls values out with the regEx /controls: ([\["a-z., \]]+,)/g
You could simply parse your input as a JSON object then loop throught the controls array:
var input='controls: ["aa.bb.cc", "dd.ee.ff"],
elements: []';
json = JSON.parse(input);
var controls=json.controls;
//then loop throught the controls values
for(var i=0;i<controls.length;i++){
console.log(controls[i]);
}
I think that should do it.
This might look like a very crude solution, but it works.
This expression will give you aa.bb.cc :
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/)[1]
and this will give the next element i.e. dd.ee.ff
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/)[2]
In general,
var str = "controls: [\"aa.bb.cc\",\"dd.ee.ff\"],elements: []";
var resLength = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/).length;
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/);
for (var i=1; i<resLength; i++) {
console.log(res[i]);
}

How to substring a string in an array in Javascript

I have function that uses a 'for loop' to find a url. Because the 'for loop' is looping over the DOM array for links, each link is placed at an array index.
The url will look like this: http://reporter.highschoolsports-555.masslive.com/news/article/4040274705063720904/title287393467/
I need to cut off the beginning of the url to look like this: highschoolsports-555.masslive.com/news/article/4040274705063720904/title287393467/
When I use substring to remove the beginning of the url, I get an error, "function substr does not exist"
Is there a way to serialize or convert the array index data into a string to that I can use substring to edit the url?
var grabLinkFromList;
var grablink= function(){
var links=document.links;
for (var i=0;i<30;i++){
console.log("index "+i+" Link "+links[i]);
if(i==23){
grabLinkFromList=links[i];
var substringURL=grabLinkFromList.substr(0,15);
alert(substringURL);
}
}
I've also used this version of substring too:
var grabLinkFromList;
var grablink= function(){
var links=document.links;
for (var i=0;i<30;i++){
console.log("index "+i+" Link "+links[i]);
if(i==23){
grabLinkFromList=links[i];
var substringURL=grabLinkFromList.substring(0,15);
alert(substringURL);
}
}

javascript - get all anchor tags and compare them to an array

I have been trying forever but it is just not working, how can I check the array of urls I got (document.getElementsByTagName('a').href;) to see if any of the websites are in another array?
getElementByTagName gives you a nodelist (an array of nodes).
var a = document.getElementsByTagName('a');
for (var idx= 0; idx < a.length; ++idx){
console.log(a[idx].href);
}
I really suggest that you use a frame work for this, like jquery. It makes your life so much easier.
Example with jquery:
$("a").each(function(){
console.log(this.href);
});
var linkcheck = (function(){
if(!Array.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]===obj){
return i;
}
}
return -1;
}
}
var url_pages = [], anchor_nodes = []; // this is where you put the resulting urls
var anchors = document.links; // your anchor collection
var i = anchors.length;
while (i--){
var a = anchors[i];
anchor_nodes.push(a); // push the node object in case that needs to change
url_pages.push(a.href); // push the href attribute to the array of hrefs
}
return {
urlsOnPage: url_pages,
anchorTags: anchor_nodes,
checkDuplicateUrls: function(url_list){
var duplicates = []; // instantiate a blank array
var j = url_list.length;
while(j--){
var x = url_list[j];
if (url_pages.indexOf(x) > -1){ // check the index of each item in the array.
duplicates.push(x); // add it to the list of duplicate urls
}
}
return duplicates; // return the list of duplicates.
},
getAnchorsForUrl: function(url){
return anchor_nodes[url_pages.indexOf(url)];
}
}
})()
// to use it:
var result = linkcheck.checkDuplicateUrls(your_array_of_urls);
This is a fairly straight forward implementation of a pure JavaScript method for achieving what I believe the spec calls for. This also uses closures to give you access to the result set at any time, in case your list of urls changes over time and the new list needs to be checked. I also added the resulting anchor tags as an array, since we are iterating them anyway, so you can change their properties on the fly. And since it might be useful to have there is a convenience method for getting the anchor tag by passing the url (first one in the result set). Per the comments below, included snippet to create indexOf for IE8 and switched document.getElementsByTagName to document.links to get dynamic list of objects.
Using Jquery u can do some thing like this-
$('a').each(function(){
if( urls.indexOf(this.href) !- -1 )
alert('match found - ' + this.href );
})
urls is the your existing array you need to compare with.

Categories

Resources