how to split the textarea into parts in javascript - 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"]

Related

javascript parse text from <a href> links

Lets say I have
ThisTextChanges
ThisTextChanges
ThisTextChanges
ThisTextChanges
I want to iterate through these and get the "ThisTextChanges" which are some numbers that changes, most accurately timers.
How can i achieve that? jquery is fine.
They are inside a div with id "main_container".
I need to put the text in a var so the href is importanto to know which var i use for each one.
Lets break the task down into several steps:
Get a handle to all of our links (document.querySelectorAll)
learn how to get the current text of an a tag (childNode[0].nodeValue)
put it all together (Array.from, Array.map)
Get a handle to all of our links:
we will use document.querySelectorAll to get list of all nodes that match our selector. here I'm just going to use the selector a, but you probably have a class that specifies these links vs other links on the page:
var links = document.querySelectorAll('a');
Get the text of a link
This one is a bit more complicated. There are several ways to do this, but one of the more efficient ways is to loop through the child nodes (which will mostly be text nodes), and append the node.nodeValue for each one. We could probably get away with just using the nodeValue of the first child, but instead we'll build a function to loop through and append each.
function getText(link){
var text = "";
for (var i = 0; i < link.childNodes.length; i++){
var n = link.childNodes[i];
if (n && n.nodeValue){
text += n.nodeValue;
}
}
return text;
}
Put it all together
To put it all together we will use Array.map to turn each link in our list into the text inside it. This will leave us with an array of strings. However in order to be able to pass it to Array.map we will have to have an array, and document.querySelectorAll returns a NodeList instead. So to convert it over we will use Array.from to turn our NodeList into an array.
function getText(link){
var text = "";
for (var i = 0; i < link.childNodes.length; i++){
var n = link.childNodes[i];
if (n && n.nodeValue){
text += n.nodeValue;
}
}
return text;
}
var linkTexts = Array.from(document.querySelectorAll('a'))
.map(getText);
console.log(linkTexts);
this is text
this is some more text
You can just add condition in the a selector as follows:
var array = [];
$('#main_container a[href="/example2"]').each(function(){
array.push($(this).html());
});
console.log(array);
You can iterate and store them in an Array
var arr = [];
$("a").each(function(){
arr.push($(this).text());
console.log( arr );
});
you can achieve that in may ways. this example using for loop.
var main_container = document.getElementById("main_container");
var items = main_container.getElementsByTagName("a");
for (var i = 0; i < items.length; ++i) {
// do something.....
}
var array = [];
$('#main_container a').each(function(){
array.push($(this).html());
});
console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main_container">
ThisTextChanges 1
ThisTextChanges 2
ThisTextChanges 3
ThisTextChanges 4
</div>
Please try:
$('#main_container > a[href]').each(function() {
var tes = $(this).attr('href').substring(1);
window[tes] = $(this).text();
});
123 will produce var named example1 with value 123, and so on.

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

Print data value of array

I have a array that has IDs in JavaScript:
["1649545","1649546","1649547"] etc.
And I want to print the values of this array in a URL, so something like this the foreach function of PHP does;
foreach
www.google.com/[valueofarray]
end
I know the solution could be very easy, but I just cannot manage to find it.
I made a fiddle and used a for loop this is without the use of jQuery but only javascript. I made an example array called myArray, I used .length so that javascript stops when he's been through all of the strings in the example array.
var myArray = ['12345', '123456', '1234567'];
for (var i = 0; i < myArray.length; i++) {
console.log('http://foo.com/' + myArray[i]);
// alert(myArray[i]);
}
See it work (and be sure to open your browsers console or use alert instead for viewing the output)
jsFiddle
var p='http:',a=["1649545","1649546","1649547"],u='www.google.com';for(i=0; i<a.length; ++i) console.log([p,'',u,a[i]].join('/'));
Try this:
var idArray = ["1649545","1649546","1649547"];
var url = "www.google.com/";
idArray.forEach(function(id){
console.log("http://" + url + id);
});
https://jsfiddle.net/tcmn2Lda/

issue with javascript for loop not executing every time

I'm using this JavaScript code for alert count in an array of pages.
urls is an array of page names, and count is the count value.
I want to alert the count value in each pages of the array urls.
But the for loop is not executing all time. I don't know what happens... Any body please help me to find out the mistake..
Am using echo $_POST['suggest']; in the array of pages. But i want to use JavaScript code for receiving the value of suggest and alert it. How to receive the value using JavaScript?
<script>
$(document).ready(function () {
var count = document.getElementById('display_visitor_number').innerHTML; //count
var urls = document.getElementById('display_visitor_urls').innerHTML; //array of page names
var myarr = urls.split(",");
for (var i=1;i<myarr.length;i++)
{
$.post(myarr[i],{suggest:count}, function(data) {
alert(data);
});
}
});
</script>
if the string urls starts with , before you split it will have an empty string as first value (this will cause jquery to make an ajax call for the current page) you may want to check for that and start with 0
<script>
$(document).ready(function () {
var count = document.getElementById('display_visitor_number').innerHTML; //count
var urls = document.getElementById('display_visitor_urls').innerHTML; //array of page names
var myarr = urls.split(",");
for (var i=0;i<myarr.length;i++)
{
if(myarr[i] !== '')$.post(myarr[i],{suggest:count}, function(data) {
alert(data);
});
}
});
</script>
instead of using split function you'd better try RegExp and match all non-space character sequences. replace
var myarr = urls.split(",");
with
var myarr = urls.match(/[^ ,]+/g)
and you should start you for loop with var i=0 then.

Categories

Resources