How to substring a string in an array in Javascript - 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);
}
}

Related

Is there a way to replace text from a JSON object after it has been stringified?

I have some JSON data which contains some urls. I'm extracting these urls from the json by looping through the objects which works fine. The urls however have 'page: ' pre-pended to them which i am trying to replace with 'https://'.
I can't get the replace property to work and give me the same result each time.
I've tried using the replace() property in different way and am using the console.log to view my results. I've also tried to stringify the JSON as I hear this is a good thing to do in order to handle it.
Each time i'm still seeing the 'page: ' word and it hasn't been replaced.
function showTopArticles(jsonObj) {
var getEntries = jsonObj.feed.entry;
var stringified = JSON.stringify(getEntries);
console.log(getEntries);
for (var i = 0; i < getEntries.length; i++) {
var list = document.createElement('article');
var articleTitle = document.createElement('li');
var articleUrl = document.createElement('a');
articleTitle.textContent = getEntries[i].title.$t;
articleUrl.textContent = getEntries[i].content.$t;
articleUrl.textContent.replace("page: ", "https://");
console.log(articleUrl.textContent);
list.appendChild(articleTitle)+list.appendChild(articleUrl);
section.appendChild(list);
}
}
I expect the output url to be 'https://www.google.com' but instead im seeing 'page : www.google.com'
replace() returns a modified value, it does not modify the original string.
You want something like:
articleUrl.textContent = articleUrl.textContent.replace("page: ", "https://");

Modifying HTTP GET Request via Select Menu Change - Update Parameter

I have a search results page in a PHP site that returns a list of results using pagination. The URL looks like this:
findProducts.php?action=searchAssets&orderNumber=xxxx&productName=zzz&skip=20
I have a select menu that allows the user to modify/filter the search results which triggers a script like this:
$(document).ready(function() {
$('#productType').change(function() {
window.location.href = window.location.href + '&productType=' + $(this).val();
});
});
This is working well except for one thing - I need to reset the 'skip' parameter to 0 for the new filter search as the pagination values from the previous search won't be valid or applicable. Is there a way I can change:
skip=20
to:
skip=0
as part of this script?
You could do a RegExp replace on the URL:
window.location.href = window.location.href.replace(/((?:\?|&)skip)=\d+/, '$1=0') + '...';
(untested)
Note that you should do the same with the productType because otherwise you'll add it again and again.
Better solution would possibly be to have a base URL and then add all necessary parameters instead of doing search and replace...
You can get the query from the URL by splitting the URL using ?
This will give you the base url in the first index and the query in the second.
You can then get the query parameters by splitting the query using &.
You can loop through all of the parameters checking if it is the skip parameter. If the parameter is the skip parameter push your new value to an output array. Otherwise push the unchanged parameter to an output array.
You can then use join to join all of your output elements using & to reconstruct the query and return your original base url with your new query string.
<script>
function fixQuery(qstr) {
var parts = qstr.split('?');
var query = parts[1];
var a= query.split("&");
var out=[];
for (var i = 0; i < a.length; i++) {
var b = a[i].split('=');
if(decodeURIComponent(b[0])=="skip")
{
out.push("skip=0")
}
else {
out.push(a[i]);
}
}
return parts[0] + '?' + out.join("&");
}
var result= fixQuery("http://example.com/findProducts.php?param1=test+thing&param2=hello&skip=10");
console.log(result)
//http://example.com/findProducts.php??param1=test+thing&param2=hello&skip=0
</script>

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);
}
}

JavaScript remove everything before a character for a URL array

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;
}

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"]

Categories

Resources