Dynamically add text strings with increasing number to a div - javascript

I'm trying add some text strings with increasing number to a div,
for example:
<div>
Text String n°: 1
Text String n°: 2
Text String n°: 3
etc...
</div>
but somethings does not work properly:
var StringsContainer = document.getElementById('StringsContainer');
var createTextStrings = function(){
var i = 0
while(i < 3){
i++;
console.log("String n°:" + (i + 1));
document.body.innerText = "String n°:" + (i + 1);
}
};
createTextStrings();
Demo: http://jsfiddle.net/Y5z6K/
In the console.log I can see a similar result, but it still not works.
Solution:
Here updated perfect result wanted: http://jsfiddle.net/Y5z6K/4/

Just change append the string:
document.body.innerText += "String n°:" + (i) +"\n";
Full code:
var StringsContainer = document.getElementById('StringsContainer');
var createTextStrings = function () {
var i = 0
while (i < 4) {
i++;
console.log("String n°:" + (i));
document.body.innerText += "String n°:" + i + "\n";
}
};
createTextStrings();
Also, you don't need i + 1 as i is already incremented.
Demo: http://jsfiddle.net/Y5z6K/1/

Concatenate the strings as you are looping:
document.body.innerText += "String n°:" + i + "\n";
Plus, you don't need to i++ then adding another i +1 when displaying it. So, just drop the +1 on the string display.
UPDATED: adding "\n" for the line change.
See the fiddle at:
JSFiddle

Try this out: http://jsfiddle.net/Y5z6K/2/
JS:
var StringsContainer = document.getElementById('StringsContainer');
var createTextStrings = function () {
var i = 0
while (i < 3) {
console.log("String n°:" + (i + 1));
document.body.innerHTML += "String n°:" + (i + 1) + "<br\>";
i++;
}
};
createTextStrings();

Related

Add class to specific multiple SPAN's

I want to add class to multiple SPAN (but not all SPAN). In this case i'm choosing to add class to last 2 SPAN's.
So currently my code is taking a string and then inserting each letter as SPAN in html.
So then i want the code to read the last 2 (or any other amount) of span to add another .class (in this case .blue)
I believe this is part of the code i need to use, but because i'm doing += it add another extra SPAN to html which is causing duplicates.
if (i >= 5) {
html += '<span class="blue blast">' + split[i] + '</span>';
}
Full code here and CodePen:
function myFunction() {
var string = document.querySelector('.title').innerHTML
var split = string.split('');
var html = '';
for (let i = 0; i < split.length; i++) {
html += '<span class="blast">' + split[i] + '</span>';
if (i >= 5) {
html += '<span class="blue blast">' + split[i] + '</span>';
}
}
document.querySelector('.title').innerHTML = html;
}
myFunction()
https://codepen.io/MariusZMM/pen/MZdpNb
I already have jQuery code that does this for me. But i want to learn Vanila JavaScript.
Update: with the help from tymeJV i have updated CodePen with a fix:
https://codepen.io/MariusZMM/pen/pqmwgL
You only want to write the blue letters when i > 5 - so wrap the other portion in an else block
if (i >= 5) {
html += '<span class="blue blast">' + split[i] + '</span>';
} else {
html += '<span class="blast">' + split[i] + '</span>';
}
This is my proposition:
function myFunction(num) {
const splitted = document.querySelector('.title').innerHTML.split('');
const newContent = splitted.map((letter, i) => {
const className = i >= splitted.length - num ? 'blue blast' : 'blast';
return '<span class="'+className+'">' + letter + '</span>';
}).join('');
document.querySelector('.title').innerHTML = newContent;
}
myFunction(3);

Concat string dynamically Javascript

I should concatenate an HTML string (i.e. "<div>HTML string</div>") to compose dinamically a description for Guider-JS.
I tried to do that using concat method but doesn't work.
var str = "<div><p>first test:</p><ul>";
for(var i=0; i<list.length;i++){
str+=("<li class='pointer' onclick=alert('hello')>" + list[i] + "</li>");
}
console.log("one " + str);
Otherwise, if I use += operator works well.
var str = "<div><p>second test:</p><ul>";
for(var i=0; i<list.length;i++){
str.concat("<li class='pointer' onclick=alert('hello')>" + list[i] + "</li>");
}
console.log("two " + str);
I have made a fiddle for explain better the case.
Sorry for my question, maybe is trivial but i don't understand why this happen
String#concat returns the new string with the concatenated values, so you want to assign that result to str: str = str.concat(...
Note that if you're using concat, you don't need + anymore:
str = str.concat("<li class='pointer' onclick=alert('hello')>", list[i], "</li>");
// -----------------------------------------------------------^^-------^^
Check the updated fiddle
make it
str = str.concat("<li class='pointer' onclick=alert('hello')>" + list[i] + "</li>");

Get Text information sort and number them an put ";" after number and after each block

Again some Problems.
I' get some values of a Textfield ,shown like them:
134.45 987.46 -89.10
224.67 127.26 -19.12
764.32 187.96 -78.25
...and so on...
I'm get them with
function LineWriteToNp01() {
var getNP01TableData = $('#null_tabelle_dues1_text').text();
}
i need them in
1;134.45;987.46;-89.10< br /><<< yes also the break - it will written in a .TXT file >>>
2;224.67;127.26;-19.12< br />
3;764.32;187.96;-78.25< br />
...and so on...
I couldn't figure it out how to. seems insoluble :(
The hekp from "guest271314" was perfekt. i've built it a Little more dynamic.
function LineWriteToNp01() {
var getNP01TableData = $('#null_tabelle_dues1_text').text().replace(/\s+X/, "");
var arr = getNP01TableData.split(/\s+/);
var _arr = [];
var index = 1;
for (var i = 1; i <= (arr.length-1)/3; i++) {
_arr.push( i + ";" + arr[index] + ";" + arr[index + 1] + ";" + arr[index + 2] + "<br />\n");
index = index + 3;
}
_arr = _arr.toString().replace(/,/g, "");
var file = new Blob([_arr], {
"type": "text/plain"
});
// ... code to write it back in txt file
}
Thanks a lot # all for your Help
Well, let's look at what you've got: you have a text block, with numbers separated by spaces. That's something we can work with.
The .split(" ") function will separate the numbers and put them in an array; you could do a
getNP01TableData.split(" ") and your result will be:
[" ", "134.45 ", "987.46 ", "-89.10", "
", "224.67 ", "127.26 ", "-19.12
", "764.32 ", "187.96 ", "-78.25" ]
And that definitely looks like something you can work with. Throw that bad boy into a loop:
var text = "";
for (var i = 0; i<arr.length/3; i++) {
text = text + i;
for (j = 0; j<3; j++) {
text=text+";"+arr[3*i + j]
}
text = text+"</br";
}
That might need a little fiddling, but you get the idea. Also, the .trim() function is useful for removing unwanted whitespace.
Try
var text = "134.45 987.46 -89.10 224.67 127.26 -19.12 764.32 187.96 -78.25";
var arr = $.map(text.split(" "), function (value, index) {
return value === "" ? null : [value]
});
var _arr = [];
_arr.push("1;" + arr.slice(0, 3).join(",").replace(/,/g, ";") + "<br />");
_arr.push("2;" + arr.slice(3, 6).join(",").replace(/,/g, ";") + "<br />");
_arr.push("3;" + arr.slice(6, 9).join(",").replace(/,/g, ";") + "<br />");
_arr = _arr.toString().replace(/,/g, "");
var file = new Blob([_arr], {
"type": "text/plain"
});
var reader = new FileReader();
reader.addEventListener("loadend", function (e) {
console.log(e.target.result);
});
reader.readAsText(file);
jsfiddle http://jsfiddle.net/guest271314/YpBxA/

How can I write in javascript a text in 2 colors? Every second letter to be red?

This is what I got so far but I`m stuck.
var s=`First JavaScript string.`;
var c=`This is second text.`;
var sc = s.concat(c);
var sp=sc.split("");
var colors=[`red`,`black`">;
for(i=0;i<sc.length;i++) {
var span=`<span style="color:`+colors[i % 2">+`;">`+sp+`</span>`;
document.write(span);
}
Don't split the string, just use sc[i] instead of sp in last line.
You are writing the text with your sp variable. What you want is the current character. In your loop you loop over every character. In this for loop the i is the index. Your sc string is actually an array of characters. Therefore sc[i] points to the current character.
If you change sp to sc[i] your code works correct.
var s = "First JavaScript string.";
var c = "This is second text.";
var sc = s.concat(c);
var colors = ['red','black'];
for (i=0; i<sc.length; i++) {
var span = '<span style="color:' + colors[i % 2] + ';">' + sc[i] + '</span>';
document.write(span);
}
However a more efficient way would be:
var s = "First JavaScript string.";
var c = "This is second text.";
var sc = s.concat(c);
var colors = ['red','black'];
var html = "";
for (i=0; i<sc.length; i++) {
html += '<span style="color:' + colors[i % 2] + ';">' +sc[i]+ '</span>';
}
document.write(html);
Fiddle at: http://jsfiddle.net/4Np9u/
Here you go:
var s = "First JavaScript string.";
var c = "This is second text.";
var sc = s.concat(c);
var colors = ['red','black'];
for (i=0; i<sc.length; i++) {
var span = '<span style="color:' + colors[i % 2] + ';">' +sc[i]+ '</span>';
document.write(span);
}
JsFiddle = http://jsfiddle.net/A24q2/

How to search for a character in a string and output the index of every place that character appears? (Javascript)

I figured it out, thank you. I need to move the body to the html. Changed some tags in the body section.
}
else
{
window.alert ("You entered an invalid character (" + enterLetter + ") please re-enter");
secondPrompt();
}
}
</script>
<body onload = "firstPrompt();">
<h2>
Word Checker
</h2>
</body>
</html>
You can increment indexOf each time you find a match-
function indexFind(string, charac){
var i= 0, found= [];
while((i= string.indexOf(charac, i))!= -1) found.push(i++);
return found;
}
indexFind('It\'s more like it is today, than it ever was before','o');
/* returned value: (Array)
6,22,48
*/
Using indexOf recursively:
function findMatches(str, char) {
var i = 0,
ret = [];
while ((i = str.indexOf(char, i)) !== -1) {
ret.push(i);
i += char.length; //can use i++ too if char is always 1 character
};
return ret;
}
Usage in your code:
var matches = findMatches(enterWord, enterLetter);
if (!matches.length) { //no matches
document.write ("String '" + enterWord + "' does not contain the letter '" + enterLetter + ".<br />");
} else {
for (var i = 0; i < matches.length; i++) {
document.write ("String '" + enterWord + "' contains the letter '" + enterLetter + "' at position " + matches[i] + ".<br />");
}
}
Live Demo
Full source (with some tweaks from your last question)

Categories