Returning customize Array value - javascript

I have a sample of code that returns each value in an array, in order. I have used forEach(). Is there any way to return value in customize array.
I made some function for split text-area value to all textarea and query using text string. I am able to success. But Some Problem. Below Example.
Type to Filed1 string like:
GFSD65897542
Then Click Split Button. Output: part all value to reaming text area.
Put GF value to Input Character Filed. Output: 6589
My Question is When i put value like GF then output 6589. And when put FG then also same output 6589 instead of 8965. If any solution Pls help me out. I wish to the Character strictly follow number.
Sample of Code:
$('#output1').focus(()=>{
var a=document.querySelectorAll('textarea');
var str = $('#ccMain').val();
var first = str[0];
var second = str[1];
console.log(first," ", second)
var str='';
a.forEach(e=>e.value.includes(first)||e.value.includes(second)?str+=e.value.substr(1,e.value.length):false)
$('#output1').val(str);
})
function splitText() {
var textAreas = [];
//Put all of the textareas into an array for easy access
for(let i = 1; i <= 4; i++) {
textAreas.push(document.getElementById(`value${i}`));
}
//Read the text from text1 and split it at a new line
var text = textAreas[0].value;
var [line1, line2] = text.split(/\r?\n/)
for(let i = 0; i < 4; i++) {
var combinedText = line1.substring(i, i+1) + line2.substring(i*2, (i+1)*2)
textAreas[i].value = combinedText;
}
}
$('#output').focus(()=>{
var a=document.querySelectorAll('textarea');
var str = $('#ccMain').val();
var first = str[0];
var second = str[1];
console.log(first," ", second)
var str='';
a.forEach(e=>e.value.includes(first)||e.value.includes(second)?str+=e.value.substr(1,e.value.length):false)
$('#output').val(str);
})
<html>
<head>
<title>Test Demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<label>Filed1 </label>
<textarea id="value1"></textarea>
<label>Filed2:</label>
<textarea id="value2"></textarea>
<label>Filed3:</label>
<textarea id="value3"></textarea>
<label>Filed4:</label>
<textarea id="value4"></textarea>
<button onclick="splitText()">Split!</button>
<br>
<label>Input Character:</label>
<br>
<input type="text" id="ccMain" >
<textarea id="output"></textarea>
</body>
</html>

I would use a map to put the correspondence between letter and digits
$('#output').focus(()=>{
var textareas = document.querySelectorAll('textarea');
var map = new Map(Array.from(textareas, area => [area.value[0], area.value.slice(1)]));
var str = Array.from($('#ccMain').val(), c => map.get(c)).join``;
$('#output').val(str);
});
function splitText() {
//Put all of the textareas into an array for easy access
var textAreas = [];
for(let i = 1; i <= 4; i++) {
textAreas.push(document.getElementById(`value${i}`));
}
//Read the text from text1 and split it at a new line
var text = textAreas[0].value;
var [line1, line2] = text.split(/\r?\n/);
for (let i = 0; i < 4; i++) {
var combinedText = line1.substring(i, i+1) + line2.substring(i*2, (i+1)*2)
textAreas[i].value = combinedText;
}
}
$('#output').focus(()=>{
var textareas = document.querySelectorAll('textarea');
var map = new Map(Array.from(textareas, area => [area.value[0], area.value.slice(1)]));
var str = Array.from($('#ccMain').val(), c => map.get(c)).join``;
$('#output').val(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Filed1 </label>
<textarea id="value1"></textarea>
<label>Filed2:</label>
<textarea id="value2"></textarea>
<label>Filed3:</label>
<textarea id="value3"></textarea>
<label>Filed4:</label>
<textarea id="value4"></textarea>
<button onclick="splitText()">Split!</button>
<br>
<label>Input Character:</label>
<br>
<input type="text" id="ccMain" >
<textarea id="output"></textarea>

Well you have to be a bit more careful in your code here, ou are defining str twice in your code block.
As far as what you want to achieve, I guess you want to go for something like
str = Array.from( a )
.filter( e => e.value.includes( first ) || e.value.includes( second ) )
.map( e => e.value.substring( 1 ) )
.join('')
this would first create an array from your nodes, using Array.from and then you can filter the values you are really interested in, after which you can take the substring of the values (you don't need the e.value.length, as this is the same as when you are just defining a startIndex in the substring method

Related

javascript printing array into paragraphs

I am trying to make a local html to display some text from txt file (also local).
I used this to read file into array and print it:
<input type="file" name="files" id="inputfile">
<script type="text/javascript">
document.getElementById('inputfile')
.addEventListener('change', function() {
var test=new FileReader();
test.onload=function(){
document.getElementById('output')
.textContent=fl.result;
}
test.readAsText(this.files[0]);
})
</script>
However, I would like to print it from the array into paragraphs, line by line (first line goes into heading, second into paragraph, third into heading and so on...).
Is there a way to do it automaticaly from an array, or would I have to do it by hand for each one?
I am kinda green in javascript so I would rather refrain from using node etc.
If the headers and paragraphs are always strictly alternating, you can check whether each array index is odd or even to decide whether to wrap it in header or paragraph tags. One way:
arr = ["header", "paragraph", "header", "paragraph", "header", "paragraph"]
joined = arr.map((el, i) => {
return (i % 2 === 0) ? `<h1>${el}</h1>` : `<p>${el}</p>` ;
}).join('')
console.log(joined)
const arr = ['Heading 1','Para1','Heading 2','Para2','Heading 3','Para3'];
const result = arr.map((val, i) => i%2===0 ? `<h2>${val}</h2>` : `<p>${val}</p>`).join('');
document.getElementById('output').innerHTML = result ;
<div id="output"></div>
Put this in your code:
function arrToPar(arr){ //For JS-Array --> HTML content
var out = "";
for(var i = 0; i < arr.length; i++){
out += arr[i] + "<br>";
}
return(out);
}
Or...
function arrToString(arr,joiner = " "){ //For JS-Array --> JS-String
var out = ""; //The parameter "joiner", by default, is a space
//This means that you only need to specify "arr", but you can do
//a second parameter. This function behaves like arr.join(joiner).
for(var i = 0; i < arr.length; i++){
out += arr[i] + joiner;
}
}

Output being not displayed as form data being not rendered (document.getElement)

<html>
<head>
</head>
<body style = "text-align:center;" id = "body">
<form id = "number" method="get" name="number">
<input type="text" id="number1" name="number1" value="" />
<input type="text" id="number2" name="number2" value="" />
</form>
<p id = "GFG_UP1" style = "font-size: 16px;">
</p>
<p id = "GFG_UP2" style = "font-size: 16px;">
</p>
<button onclick = "gfg_Run()">
Convert
</button>
<p id = "GFG_DOWN1" style = "color:red;
font-size: 20px; font-weight: bold;">
</p>
<p id = "GFG_DOWN2" style = "color:red;
font-size: 20px; font-weight: bold;">
</p>
<script>
var form = document.getElementById('number');
var el_up1 = document.getElementById("GFG_UP1");
var el_up2 = document.getElementById("GFG_UP2");
var el_down1 = document.getElementById("GFG_DOWN1");
var el_down2 = document.getElementById("GFG_DOWN2");
var array1 = form.elements.number1.value;
var array2 = form.elements.number2.value;
var numberArray1 = [];
var numberArray2 = [];
for (i = 0; i < array1.length; i++)
{
numberArray1[i] = "Phone" + i + ':'+array1[i];
}
el_up1.innerHTML = "Array = [" +array1+"]";;
a = i;
for (i = 0 ; i < array2.length; i++)
{
numberArray2[i] = "Phone" + a + ':'+array2[i];
a++;
}
el_up2.innerHTML = "Array = [" +array2+"]";;
function gfg_Run(){
el_down1.innerHTML =
JSON.stringify(Object.assign(numberArray1));
el_down2.innerHTML =
JSON.stringify(Object.assign(numberArray2));
}
</script>
</body>
</html>
the following code should give output of two json arrays ["number0:34","number1:24","number2:31","number3:48"]
["number0:23","number1:43","number2:65","number3:52"]
when numbers are given input in the form but no output being shown as in the script both arrays are not able to read data by the form .
error lies in the array as if i pass directly value in array in script it runs fine
help me in debug if u can
I don't think this is a complete answer to your question, but the first thing I notice is that in your for loops, you're trying to use the .length properties of array1 and array2, which aren't actually arrays:
var array1 = form.elements.number1.value;
var array2 = form.elements.number2.value;
You're setting them to the .value properties of the two inputs, which are theoretically going to be digits, but taken as strings by the .value property, because the input type is set to "text".
So Here's what I would do instead:
var form = document.getElementById('number');
var el_up1 = document.getElementById("GFG_UP1");
var el_up2 = document.getElementById("GFG_UP2");
var el_down1 = document.getElementById("GFG_DOWN1");
var el_down2 = document.getElementById("GFG_DOWN2");
/* grab the values from those text inputs, and parse them into integers (because
they will be strings because the input type is set to "text") */
var input1 = parseInt(form.elements.number1.value);
var input2= parseInt(form.elements.number2.value);
/* I also changed the names to input1 and input2 because it's confusing to have them
labeled as 'arrays' when they're actually integers */
var numberArray1 = [];
var numberArray2 = [];
/* now just use those numerical values as your exit condition in your loops */
for (i = 0; i < input1; i++)
{
/* we're also going to use Array.push() to add vlues to the `numberarray` instead of trying to assign a value to the element at "i" */
numberArray1.push("Phone" + i + ':'+ (i+1));
}
/* I'm not 100% sure what you were trying to do here, but I'm guessing that you
actually want to show the values 'numberArray1' here instead of the value of that
first input, so we'll use the 'spread' operator to put that in there */
el_up1.innerHTML = `Array = [${...numberArray1}]`;
a = i;
for (i = 0 ; i < input2; i++)
{
numberArray2.push("Phone" + a + ':'+ (i+1));
a++;
}
el_up2.innerHTML = `Array = [${...numberArray1}]`;
function gfg_Run(){
el_down1.innerHTML =
JSON.stringify(Object.assign(numberArray1));
el_down2.innerHTML =
JSON.stringify(Object.assign(numberArray2));

Regex.replace() not working after appending child

I am trying to build a basic mad lib style code using Regex and I am unable to create new input elements and have them behave like the initial one.
I've tried swapping out (doc.replace(regex[i]... for (doc.replace(inputArray[i]... - this works partially, but in the end I am stuck with brackets around the input value.
<!-- HTML
<div id = "doc" contentEditable="true">{input1} {input2}</div>
<div id = "inputs">
<input type = "text" id = "input1"> {input1}
</div>
<br>
<button onclick="generate()">Generate</button>
<button onclick="addInput()">Add Input</button>
</div>
-->
//Global Variables
var inputNumber = 1;
var regex = [/{input1}/g];
var inputArray = ["input1"];
//Generate
function generate(){
for (var i = 0; i < inputArray.length; i++) {
var doc = document.getElementById("doc").innerHTML;
var outputArray = document.getElementById(inputArray[i]).value;
document.getElementById("doc").innerHTML = (doc.replace(regex[i], outputArray))
};
};
//Add Input
function addInput(){
inputNumber++;
var inputs = document.getElementById("inputs");
var newInput = document.createElement("div");
newInput.innerHTML = "<p><input type='text' id='input"+inputNumber+"'> {input"+inputNumber+"}</p>";
inputs.appendChild(newInput);
inputArray.push("input"+inputNumber);
regex.push("/{input"+inputNumber+"}/g")
};
I want {input2} to become the value of the input with the id of 'input2' when the function generate() is called. It just straight up doesn't work.
Here my code snippet for test.
//Global Variables
// RegEx save input
var regexInputs = /\{(input\d+)\}/g;
//Generate
function generate(){
var doc = document.getElementById("doc");
var inputs = doc.innerHTML.matchAll(regexInputs);
var input = inputs.next();
while(input.value){
doc.innerHTML = doc.innerHTML.replace(
input.value[0], document.getElementById(input.value[1]).value);
input = inputs.next();
};
}
function addInput(){
var inputs = document.getElementById("inputs");
var idxInput = inputs.children.length + 1;
var newInput = document.createElement("div");
newInput.innerHTML = "<p><input type='text' id='input"+ idxInput +"'> {input"+ idxInput +"}</p>";
inputs.appendChild(newInput);
}
<div id = "doc" contentEditable="true">{input1} {input2}</div>
<div id = "inputs">
<input type = "text" id = "input1"> {input1}
</div>
<br>
<button onclick="generate()">Generate</button>
<button onclick="addInput()">Add Input</button>
</div>
<script src="script.js" type="text/javascript"></script>
Notes:
The regexInputs is the pattern that match all inputs and store (input\d+), so using matchAll we go througth all matches.
Every match has two index 0 has "{input#}" and 1 has "input#". With this strings we just do replaces.

Write multiple strings on the same id [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Let's say I have the input of 'Fred'.
How can I print it so that it looks like this?
Character List:
F
r
e
d
And that it is all being written to a paragraph element in html with the id = 'msg2'
So far all that I can get it to write is either F or d
Apologies, forgot to include code
function start () {
var vName = document.getElementById('custname').value;
var vLength = processString(vName);
document.getElementById('msg1').innerHTML = vName;
document.getElementById('msg2').innerHTML = vLength;
}
function processString (pString) {
for (i = 0; i < pString.length; i++) {
t = i + 1
var vReturnName = ('Character list: <br />' + (pString.substring(i, t)))
}
return (vReturnName);
}
Split the string and use forEach to loop over the array then create new element and just put it in the DOM:
let str = "FRED";
str.split('').forEach(s => {
let p = document.createElement('p');
p.textContent = s;
document.body.appendChild(p);
})
p{border-bottom:solid 1px #c8c8c8;}
Your code has few issues:
var vReturnName = inside loop will always have last value as you are overriding it. Move declaration outside loop and the use vReturnName += to append
(pString.substring(i, t)) This will give you single character but you are not adding <br/> after it and so you will have no line-breaks. Also you can use string.charAt instead of it.
for (i = 0; Any variable defined without var|let|const becomes global.
function start() {
var vName = document.getElementById('custname').value;
var vLength = processString(vName);
document.getElementById('msg1').innerHTML = vName;
document.getElementById('msg2').innerHTML = vLength;
}
function processString(pString) {
var vReturnName = 'Character list: <br />'
for (i = 0; i < pString.length; i++) {
t = i + 1
vReturnName += (pString.substring(i, t) + "<br/>")
}
return (vReturnName);
}
<input type="text" id="custname" />
<button onclick="start()">Process String</button>
<div id="msg1"></div>
<div id="msg2"></div>
Alternate solution:
function start() {
var vName = document.getElementById('custname').value;
var vLength = processString(vName);
document.getElementById('msg1').innerHTML = vName;
document.getElementById('msg2').innerHTML = vLength;
}
function processString(pString) {
var vReturnName = wrapInP('Character list:')
for (var i = 0; i < pString.length; i++) {
vReturnName += wrapInP(pString.charAt(i))
}
return vReturnName;
}
function wrapInP(str){
return "<p>" + str + "</p>"
}
<input type="text" id="custname" />
<button onclick="start()">Process String</button>
<div id="msg1"></div>
<div id="msg2"></div>
References:
Is it sometimes bad to use <BR />?
string.charAt(x) or string[x]?
Use String#split to get array of each character.
Use Array#join to get the string concatenated with <br><br>
var name = "Fred";
var newName = name.split('').join('<br><br>');
document.getElementById('msg2').innerHTML = newName;
<div id='msg2'></div>
You have to split up the text and append it to the div like so:
var string = 'Fred';
var characters = string.split('');
for(var i=0; i< characters.length; i++)
{
$('#msg2').append(characters[i]+'<br/>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = 'msg2'></div>
If using Pure JS:
var string = 'Fred';
var characters = string.split('');
for(var i=0; i< characters.length; i++)
{
document.getElementById('msg2').innerHTML+=characters[i]+'<br/>';
}
<div id = 'msg2'></div>

find { or } inside an element and wrap them with span

<div id = "board>
<div>{abc</div>
<div>def</div>
<div>ghi}</div>
</div>
I've already done this by span-wrapping all of the char first before comparing if it is { or }. But that is too slow, i need to reverse the procedure, is it possible to get the char position relative to the parent div?
Intended Output is
<div id = "board>
<div><span>{</span>abc</div>
<div>def</div>
<div>ghi<span>}</span></div>
</div>
how about using contains() and replace()?
You want to use Regular Expressions:
var x = '<div id = "board>' +
'<div>{abc</div>' +
'<div>def</div>' +
'<div>ghi}</div>' +
'</div>'; // or... get element by id 'board'
var rgx1 = /{/;
var rgx2 = /}/;
var y = x.replace(rgx1, "<span>{</span>");
y = y.replace(rgx2, "<span>}</span>");
if you think you have more than 1 occurrence of { or }, you can add "g" to the regex's:
var rgx1 = /{/g;
var rgx2 = /}/g;
Assuming this is the markup:
<div id="board">
<div>{abc</div>
<div>def</div>
<div>ghi}<div>
</div>
And your intended output is:
<div id="board">
<span>abcdefghi</span>
</div>
You can do this using jQuery/javascript like this:
var textNodes = $("#board").find("div");
var text = "";
for(var i=0;i<textNodes.length;i++) {
text = text + textNodes[i].text();
$("#board").remove(textNodes[i]);
}
var spans = text.split("}");
var textToAppend = "";
for(i=0;i<spans.length - 1 ;i++)
textToAppend = textToAppend + "<span>"+spans[i].split("{")[1]+"</span>";
$("#board").append(textToAppend);
Is this the solution you are looking for?
Edit 1:
If you need just the position of lets say b as 2, and d as 4?
Here is the code.
var textNodes = $("#board").find("div");
var text = "";
for(var i=0;i<textNodes.length;i++) {
text = text + textNodes[i].text();
}
var codeBlocks = text.split("}");
var firstBlock = codeBlocks[0];
var getCharPosInBlock = function (character) {
if(character === "}") return firstBlock.length;
return firstBlock.indexOf(character);
}
To get the required result using javascript looping:
var textNodes = $("#board").find("div");
for(var i=0;i<textNodes.length;i++) {
var value = textNodes[i].text()
if(value.indexOf("{") > 0)
textNodes[i].text(value.replace("{", "<span>{</span>"));
if(value.indexOf("}") > 0)
textNodes[i].text(value.replace("{", "<span>}</span>"));
}

Categories