JavaScript Looping Through Array, Combining After [duplicate] - javascript

This question already has answers here:
Javascript split, push and join
(2 answers)
Closed 6 years ago.
I get a string of data back that is seperata by semi colons. Here is an example:
apple;orange;lemon).
I am trying to strip out the semi colons and turn the string into an array, so I can access each item individually. Then, I am trying to join them back together and print them out on the screen separated by a "/". The problem is that it is not working.
var planArray = associatedAction.split(";")
for(var i=0; i < planArray.length; i++) {
var seperatedActionPlan = planArray[i];
}
Also, I would like to put the final output into a variable, so I can print out just that variable on the page.
Please help!
EDIT!
One thing I forgot to mentioned, is that when the string prints out, I want the values to be separated. So as an example I want the final print out to be Apple/Orange/Lemon

I think this is what you are looking for:
<script type="text/javascript">
var associatedAction = "a;b;c;d";
var planArray = associatedAction.split(";")
var seperatedActionPlan = '';
for (var i = 0; i < planArray.length; i++) {
if (i < planArray.length - 1) {
seperatedActionPlan =
seperatedActionPlan.concat(planArray[i] + "/");
}
else {
seperatedActionPlan = seperatedActionPlan.concat(planArray[i]);
}
}
alert(seperatedActionPlan);
</script>

this should work
var seperatedActionPlan = planArray.join("/")

let seperatedActionPlan = associatedAction.split(";").join("/"));
Should do it.

Change your code to this:
var planArray = associatedAction.split(";"),
seperatedActionPlan;
for(var i=0; i < planArray.length; i++) {
// ... do what you need
}
seperatedActionPlan = planArray.join('/');
// print out seperatedActionPlan
or if you don't do anything to the array except splitting and joining with / just use
var seperatedActionPlan = associatedAction.replace(';', '/');
// print out seperatedActionPlan

This help you :
<html>
<head>
</head>
<body>
<script>
var associatedAction = "apple;orange;lemon";
var planArray = associatedAction.split(";")
for(var i = 0; i < planArray.length; i++ ) {
var a = document.createElement('a');
var txt = document.createTextNode("/");
a.href = "#";
a.innerHTML = planArray[i];
document.body.appendChild(a);
if (i != planArray.length - 1)
a.insertAdjacentHTML('afterend',"/");
}
</script>
</body>
</html>

Related

Return array type from stack or table - Javascript

I have a problem with my code. Maybe simple, maybe not - for first lets look at this.
var tab = [];
do{
var i = 0;
tab.push(prompt("Write some type of array!"));
i++;
}while(confirm("Next array?"));
for (var i=0; i<tab.length; i++)
document.write(typeof(tab[i])+"<br>");
<!DOCTYPE HTML>
<HTML>
<HEAD>
<meta charset="utf-8">
<meta name="author" content="Donio3d">
</HEAD>
<BODY>
</BODY>
<script src="script.js"></script>
</HTML>
So i want to return a type of array from stack. Everything is always a string.
Is there any way to do this, without checking by IF statement?
To get the typeof of the input you have to first checking if it is a number using Number.isNaN() and for simplicity also used Unary plus (+) operator.
Code:
const tab = [];
const getInputTyeof = i => typeof (!Number.isNaN(+i) ? +i : i);
do {
tab.push(prompt('Write some type of array!'));
} while (confirm('Next array?'));
tab.forEach(input => document.write(getInputTyeof(input) + '<br>'));
Since promt will always return a string in your example you have to figure out if the input may represent a other type or not, using something like this:
var tab = [];
do{
var i = 0;
tab.push(parseType(prompt("Write some type of array!")));
i++;
}while(confirm("Next array?"));
for (var i=0; i<tab.length; i++){
document.write((typeof tab[i])+"<br>");
}
function parseType(e){
if(parseFloat(e) == e && Number.isFinite(parseFloat(e))){
return parseFloat(e);
}
return e;
}
prompt will always return you a string type so you need to make a custom logic with isNaN() to separate out the string and integer values. Something like this below:
var tab = [];
do{
var i = 0;
tab.push(prompt("Write some type of array!"));
i++;
}while(confirm("Next array?"));
var integerType = [];
var stringType = [];
for (var i=0; i<tab.length; i++){
if(isNaN(tab[i])){
stringType.push(tab[i]);
} else {
integerType.push(tab[i]);
}
}
console.log('Integer type array ' + integerType);
console.log('String type array ' + stringType);
var tab = [];
do{
var i = 0;
tab.push(parseType(prompt("Write some type of array!")));
i++;
}while(confirm("Next array?"));
for (var i=0; i<tab.length; i++){
document.write((typeof tab[i])+"<br>");
}
function parseType(e){
if(parseFloat(e) == e && Number.isFinite(parseFloat(e))){
return parseFloat(e);
}
return e;
}
Hey! That is exacly what i was looking for. Thanks for help!

Get all text from a Div after a '-' up until the first character

I'm trying to write a function that will find an instance of text within a div and console.log all text that is after the '-' character. After the '-' character there are sometimes spaces and tabs, so I want to remove these up until the first text character. Here's what I have so far (that is not working at all):
var countryData = $(".countries-title").next().text();
//var regex = /(?<= - ).*/g;
let stringArray = countryData.replace(/\t/g, '').split('\r\n');
console.log(stringArray);
Any help is appreciated. Thanks
console.log('here is a - whole bunch of text'.match(/-\s*(.*)$/)[1]) will log out "whole bunch of text". Is that along the lines of what you are looking for? Let me know if you want me to elaborate.
Assuming you want to maintain all hyphens and formatting after the first hyphen and subsequent spaces you could use:
let textAfterHyphen = countryData.replace(/\s*-\s*/, '');
I am not sure if I understood all but here you have my solution:
$(document).ready(function returnString() {
$("#click-target").on("click",function(){
var newString = [];
var resultString = [];
var onlyChar =$(".target").text();
newString = onlyChar.split("");
for(var i = 0; i < newString.length; i++){
if(newString[i] == "-"){
resultString = newString.slice(i+1,newString.length).join("");
}
}
var k = 0;
for(var j = 0; j < resultString.length; j++){
if(resultString.charCodeAt(j) > 64 && resultString.charCodeAt(j) < 91){
k += j;
}
}
console.log(resultString.slice(k,resultString.length));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="target">Text- *^^^***Text to display</div>
<button id ="click-target">Click</button>

Greasemonky: How to return count and value of specific div class?

Lets say I have the following on a page:
<div class="data-container">John</div>
<div class="data-container">Dave</div>
<div class="data-container">Bob</div>
How can I use a javascript in greasemonkey to count each "data-container" class, extract the value (i.e. John) and display this info as a popup? like so:
1) John
2) Dave
3) Bob
Here is what I got so far that isn't working:
var elements = document.getElementsByClass("data-container");
for(var i=0;i<elements.length;i++){
document.body.innerHTML= document.body.innerHTML.replace(/<div class=\"data-container\">/g,"<p style=\"text-align: center;\"><span style=\"font-size:16px;\"><strong><span style=\"background-color:#ffff00;\">"+ elements[i].className + "</span></strong></span></p><div class=\"data-container\">");
}
Edit
Thanks cbwll! here is my current working code:
var elements = document.getElementsByClassName("data-container");
var contents = [];
var run = [];
for (var i = 0; i < elements.length; i++) {
contents += elements[i].textContent;
run += i;
final = run + contents;
}
alert(JSON.stringify(final));
it produces:
0123johndavebobevan
which is 0,1,2,3 & John, Dave, Bob, Evan
Any ideas on how the get them paired correctly then get a "\n" in there?
var elements = document.getElementsByClass("class");
var contents = [];
for (var i = 0; i < elements.length; i++) {
contents += elements[i].textContent;
}
//contents would be an array containing the names given in your example.

get all variations of a string javascript

I want to get all the variations of a certain string. This string will be broken up by dashes. And the letters can only vary within those dashes.
For instance, let's say I pass DFI3-334-FG12 then I want to get all variations of that string for instance:
FI3-334-G12
FI3-334-F12
FI3-334-FG2
FI3-334-FG1
DI3-334-G12
DI3-334-F12
DI3-334-FG2
DI3-334-FG1
DF3-334-G12
DF3-334-F12
DF3-334-FG2
DF3-334-FG1
DFI-334-G12
DFI-334-F12
DFI-334-FG2
DFI-334-FG1
Can anyone assist with this? I have attempted loops but I only get as far as breaking it up and getting different parts of it:
FI3,DI3,DF3,DFI
334
G12,F12,FG2,FG1
This is my code:
$('#filter').on('click',function() {
var input = $('#code').val();
var parts = input.split("-");
var fixed = Array();
for(var i=0;i<parts.length; i++) {
if(parts[i].length != 3) {
k = 0;
fixed[i] = new Array();
for(var c=0;c<parts[i].length;c++) {
fixed[i][k] = parts[i].replace(parts[i].charAt(c),"");
k++;
}
} else {
fixed[i] = parts[i];
}
}
var final = Array();
$.each(fixed,function(i) {
$('#code_result').append(fixed[i] + "<br>");
})
});
If you know how many segments there are (3 in this case), you can use loops to get every possible combination.
See my example here:
http://jsfiddle.net/a6647m9e/1/
for(var i=0; i<parts[0].length; ++i) {
for(var j=0; j<parts[1].length; ++j) {
for(var k=0; k<parts[2].length; ++k) {
strings.push(parts[0][i]+'-'+parts[1][j]+'-'+parts[2][k]);
}
}
}
And just so you know, you're looking at (2^parts[0].length - 1) * (2^parts[1].length - 1) * (2^parts[2].length - 1) combinations (1575 in this case), taking out the blank combinations.
Note: this is all dependent on what your definition of "all possible combinations" is.
var string= 'DFI3-334-FG12';
var parts = string.split('-');
for(var i=0;i<parts[0].length;i++)
for(var j=0;j<parts[2].length;j++){
p1 = parts[0].substring(0,i)+parts[0].substring(i+1,parts[0].length);
p2 = parts[2].substring(0,j)+parts[2].substring(j+1,parts[2].length);
console.log(p1+'-'+parts[1]+'-'+p2);
}

Generate Array Javascript

I want to generate an array in jQuery/JS, which contains "code"+[0-9] or [a-z].
So it will look like that.
code0, code1 ..., codeA, codeB
The only working way now is to write them manually and I am sure this is a dumb way and there is a way to generate this automatically.
If you give an answer with a reference to some article where I can learn how to do similar stuff, I would be grateful.
Thank you.
For a-z using the ASCII table and the JavaScript fromCharCode() function:
var a = [];
for(var i=97; i<=122; i++)
{
a.push("code" + String.fromCharCode(i));
}
For 0-9:
var a = [];
for(var i=0; i<=9; i++)
{
a.push("code" + i);
}
I'm using the unicode hexcode to loop through the whole symbols from 0-z:
var arr = [];
for (var i = 0x30; i < 0x7b;i++){
// skip non word characters
// without regex, faster, but not as elegant:
// if(i==0x3a){i=0x41}
// if(i==0x5b){i=0x61}
char = String.fromCharCode(i);
while(!/\w/.test(char)){char = String.fromCharCode(i++)};
// generate your code
var res = "code"+char;
// use your result
arr.push(res);
}
console.log(arr);
Here goes your example.
Docs:
Unicode Table
for loop
fromCharCode
JS Array and it's methods
you can generate array in javascript by using following code.
var arr = [];
for (var i = 0; i < 5; i++) {
arr.push("code"+ i);
}
please refer following links.
https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/Array
http://www.scriptingmaster.com/javascript/JavaScript-arrays.asp
a = [];
for(i = 48; i < 91; i++) {
if (i==58) i = 65
a.push("code" + String.fromCharCode(i));
}
alert(a.join(',')) // or cou can print to console of browser: console.log(a);

Categories

Resources