Javascript string formatting - replace in string saved in a variable - javascript

Task is simple write numbers from 1 to 99 and replace all numbers where: num (mod 3) =0 with each num (mod 5) =0 -> mat, num ( mod 3=0 && mod 5=0 ) with each mat, all others remains the same. That is easy but the formatting is horrible so I want to do this: insert a space between every number and place every "special" word (dividable by 3,5 or both) on a separate line. I know I have to use string.prototype.format but how exactly? here is my current code:
<html>
<body>
<p>Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = [];
var res = " ";
for (i=1; i<100; i++){
if (i%3 == 0 && i%5 == 0){
text[i]= "SachMat ";
}
else if (i%3 == 0){
text[i]= 'sach ';
}
else if (i%5 == 0){
text[i]= 'mat ';
}
else {
text[i]= i;
}
var res = res.concat(text[i]);
}
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>

Try this
function myFunction() {
var text = [];
var res = " ";
for (i=1; i<100; i++){
if (i%3 == 0 && i%5 == 0){
text[i]= "<br/>SachMat<br/>";
} else if (i%3 == 0) {
text[i]= 'sach ';
} else if (i%5 == 0){
text[i]= 'mat ';
} else {
text[i]= i;
}
res = res.concat(' ' + text[i]);
}
document.getElementById("demo").innerHTML = res;
}

Related

Printing For Loop Is One Number Off Each Time

I'm playing around with some HTML and Javascript. I'm trying to print out 100 numbers on a screen after I press a button on a webpage. I can get the numbers to print on the screen but when I want to replace a number with a string like "Apple" if the number is divisible by 5. The code is below:
function testFunction() {
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = -1; i < 20; i++) {
if (i % 5 == 0 && i % 3 == 0) {
myHTML += '<span class="test">Pineapple</span><br/>';
} else if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br/>';
} else if (i % 3 == 0) {
myHTML += '<span class="test">Pine</span><br/>';
} else {
myHTML += '<span class="test">' + (i + 1) + '</span><br/>';
}
}
wrapper.innerHTML = myHTML
}
The output is always off by one element so it would print "5" and then the next line would be "Apple" instead of replacing "5" with "Apple" and then printing "6"
Here is the output:
0
Pineapple
2
3
Pine
5
Apple
Pine
8
9
Pine
Apple
12
Pine
14
15
Pineapple
17
18
Pine
20
You are printing i+1, instead of i.
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = -1; i < 20; i++) {
if (i % 5 == 0 && i % 3 == 0) {
myHTML += '<span class="test">Pineapple</span><br/>';
} else if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br/>';
} else if (i % 3 == 0) {
myHTML += '<span class="test">Pine</span><br/>';
} else {
myHTML += '<span class="test">' + (i ) + '</span><br/>';
}
}
wrapper.innerHTML = myHTML
}
The trouble is in the starting point of your for loop, where you initialize with -1 instead of 0. While you use (i + 1) at the end when you print a number, which is why it causes your results to be one number off.
Use for(var i = 0; i <= 20; i++) instead of for (var i = -1; i < 20; i++) when you want to loop 20 times.
function testFunction() {
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = 0; i <= 20; i++) {
if (i % 5 == 0 && i % 3 == 0) {
myHTML += '<span class="test">Pineapple</span><br/>';
} else if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br/>';
} else if (i % 3 == 0) {
myHTML += '<span class="test">Pine</span><br/>';
} else {
myHTML += '<span class="test">' + i + '</span><br/>';
}
}
wrapper.innerHTML = myHTML
}
Using this code I was able to replace 5 with Apple.
function testFunction() {
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = -1; i < 20; i++){
if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br>';
} else{
myHTML += '<span class="test">' + i + '</span><br>'
}
}
wrapper.innerHTML = myHTML
}
testFunction();
<div id="Test"></div>
Use this snippet to follow what exactly happens within your loop. It should give you some clues.
const log = Logger();
testFunction();
function testFunction() {
for (let i = -1; i < 20; i += 1) {
if (i % 5 == 0 && i % 3 == 0) {
log(`${i} % 5 === 0 && ${i} % 3 === 0 => Pineapple`);
} else if (i % 5 == 0) {
log(`${i} % 5 === 0 => Apple` );
} else if (i % 3 == 0) {
log(`${i} % 3 === 0 => Pine`);
} else {
log(`i = ${i}, i + 1 = ${i + 1}`);
}
}
}
function Logger() {
let logEl;
if (typeof window === "object") {
logEl = document.querySelector("#log") || (() => {
document.body.appendChild(Object.assign( document.createElement('pre'), { id: "log" }) );
return document.querySelector("#log");
})();
return (...logLines) => logLines.forEach(s => logEl.textContent += `${s}\n`);
} else {
return (...logLines) => logLines.forEach(ll => console.log(`* `, ll));
}
}

Letter decode Javascript

I am trying to write a function that will validate that all entries within the commas are numberic and display "?" if they are not. for example: user enters 2,3,5b,c7 the output that I am getting is BCE? instead of BC?? This is the decode function that I am trying to validate in:
function fnDecode() {
var msg = $("textin").value;
if(msg === "") {
$("textin_span").innerHTML = "* Please enter a value to decode
*";
$("textin").focus();
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(","); //split method separates by delimiter
var outstr = ""; //out string
for (var i=0; i<nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) { //if isNaN true, print ?
outstr += "?";
} else if (isNallN(nums[i])) { //THIS IS WHERE THE FN GOES
outstr += "?";
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 >26) {
outstr += "?";
}else {
outstr += String.fromCharCode(n2+64);
}
}
$("textout").value = outstr;
}
function isNallN(s) {
}
I corrected your fnDecode function.
You don't need multiple if to check for isNaN, !isNaN('5') will work as well as !isNaN(5). Check this Javascript Equality Table for more information.
Here, I adapted the function for it to work with a String given in
parameter and to return the wanted String.
function fnDecode(msg) {
var nums = msg.split(",");
var outstr = "";
for (num of nums) {
if (isNaN(num)) outstr += "?"; //isNaN works on "5" and 5
else if (+num === 0) outstr += " "; //We use +num to parse the String to an int
else if (+num < 1 || +num > 26) outstr += "?";
else outstr += String.fromCharCode(+num + 64);
}
return outstr;
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a shorter ES6 version :
function fnDecode(msg) {
return msg.split(',').map( num => isNaN(num) || (+num < 1 || +num > 26) ? '?' : +num == 0 ? ' ' : String.fromCharCode(+num + 64)).join('');
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));

Trying to print the right answer in Javascript using getElementById

I'm trying to find whether or a not a number is a perfect number, but I can't get it to print right. The numbers 6, 496, 8128 are perfect numbers but when I entered those it kept printing from var res2 instead of var res1. What's the problem here, can anyone can help?
function perfectNo(number) {
var temp = 0;
var res1 = "It is a perfect number";
var res2 = "It is not a perfect number";
for (var i = 1; i <= number / 2; i++) {
if (number % i == 0) {
temp += i;
}
}
if (temp == number && temp != 0) {
document.getElementById("results").innerHTML = res1;
} else {
document.getElementById("results").innerHTML = res2;
}
}
<input id="num">
<input type="button" onclick="perfectNo()" value="check">
<br>
<p>Answer:</p>
<p id="results"></p>
<br>
Try with :
var number = document.getElementById("num").value;
Like this :
function perfectNo() {
var number = document.getElementById("num").value;
console.log(number);
var temp = 0;
var res1 = "It is a perfect number";
var res2 = "It is not a perfect number";
for (var i = 1; i <= number / 2; i++) {
if (number % i == 0) {
temp += i;
}
}
if (temp == number && temp != 0) {
document.getElementById("results").innerHTML = res1;
} else {
document.getElementById("results").innerHTML = res2;
}
}
<input id="num">
<input type="button" onclick="perfectNo()" value="check">
<br>
<p>Answer:</p>
<p id="results"></p>
<br>

Game of life in JavaScript - using Table

I finished coding Conway's Game of Life in JavaScript and HTML table.
logic cells in a table will be assigned with unique id's and based on the id operations(based 4 rules) take place.
You can find the working code at Codepen or i have put the code below.
The thing is it works well with any number of rows and 9 columns and if more than 9 columns are given their wont be unique id's so it works in undesired manner.
Query Is their a way where i can assign the whole table with unique id's.
Code block tableInitialization is the initialization part.
(function(){
$(document).ready(function(){
var column = "", appendRow = "", inc = 1, selectedCells = [], toRemoveClass = [], toAddClass = [], maxValue;
var tableInitialization = function(noOfRow, noOfColumn){
for(var row=1; row<=noOfRow; row++){
for(var col=1; col<=noOfColumn; col++){
column += "<td id =" + inc+col + "> </td>";
}
appendRow += "<tr>"+column+"</tr>";
column= "";
inc++;
}
$(".table").append(appendRow);
};
$("#submit").click(function(data){
var noOfRow = parseInt($("#rowNo").val());
var noOfColumn = parseInt($("#columnNo").val());
maxValue = parseInt(noOfRow.toString() + noOfColumn.toString());
if(isNaN(noOfRow) || isNaN(noOfColumn)){
alert("Please enter number");
} else {
tableInitialization(noOfRow, noOfColumn);
$("#container").hide();
$("td").click( function(data){
selectedCells.push(parseInt(this.id));
$(this).addClass("valid");
});
}
});
var checkAgain = function(selectedCells){
var check = 0, toBeReplaced = [], inArray = [], livingCell;
var currentNumber = 0;
var north, northEast, East, southEast, south, southWest, west, northWest;
for(var i=0; i<selectedCells.length; i++){
check = 0;
currentNumber = parseInt(selectedCells[i]);
if($("#"+(currentNumber)).hasClass("valid")){
livingCell = true;
} else {
livingCell = false;
}
if(currentNumber > 0 && currentNumber < maxValue){
/*North*/
if((currentNumber-10) > 0 && (currentNumber-10) < maxValue){
if($("#"+(currentNumber-10)).hasClass("valid")){
check ++;
}
}
/*North East*/
if((currentNumber-9) > 0 && (currentNumber-9) < maxValue){
if($("#"+(currentNumber-9)).hasClass("valid")){
check ++;
}
}
/*East*/
if((currentNumber+1) > 0 && (currentNumber+1) < maxValue){
if($("#"+(currentNumber+1)).hasClass("valid")){
check ++;
}
}
/*South East*/
if((currentNumber+11) > 0 && (currentNumber+11) < maxValue){
if($("#"+(currentNumber+11)).hasClass("valid")){
check ++;
}
}
/*South*/
if((currentNumber+10) > 0 && (currentNumber+10) < maxValue){
if($("#"+(currentNumber+10)).hasClass("valid")){
check ++;
}
}
/*South West*/
if((currentNumber+9) > 0 && (currentNumber+9) < maxValue){
if($("#"+(currentNumber+9)).hasClass("valid")){
check ++;
}
}
/*West*/
if((currentNumber-1) > 0 && (currentNumber-1) < maxValue){
if($("#"+(currentNumber-1)).hasClass("valid")){
check ++;
}
}
/*North West*/
if((currentNumber-11) > 0 && (currentNumber-11) < maxValue){
if($("#"+(currentNumber-11)).hasClass("valid")){
check ++;
}
}
if(livingCell){
if(check === 0 || check === 1 ){
if(toRemoveClass.indexOf(currentNumber) == -1){
toRemoveClass.push(currentNumber);
}
}
if(check == 4 || check == 5 || check == 6 || check == 7 || check == 8 ){
if(toRemoveClass.indexOf(currentNumber) == -1){
toRemoveClass.push(currentNumber);
}
}
if(check == 2 || check == 3){
if(toAddClass.indexOf(currentNumber) == -1){
toAddClass.push(currentNumber);
}
}
} else {
if(check == 3){
if(toAddClass.indexOf(currentNumber) == -1){
toAddClass.push(currentNumber);
}
}
}
}
}
};
var gol = function(selectedCells){
var check = 0, inArray = [];
var currentNumber = 0, livingCell;
for(var i=0; i<selectedCells.length; i++){
toBeReplaced = [];
check = 0;
currentNumber = parseInt(selectedCells[i]);
if($("#"+(currentNumber)).hasClass("valid")){
livingCell = true;
} else {
livingCell = false;
}
if(currentNumber > 0 && currentNumber < maxValue){
/*North*/
if((currentNumber-10) > 0 && (currentNumber-10) < maxValue){
if($("#"+(currentNumber-10)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber-10)) == -1){
toBeReplaced.push(currentNumber-10);
}
}
/*North East*/
if((currentNumber-9) > 0 && (currentNumber-9) < maxValue){
if($("#"+(currentNumber-9)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber-9)) == -1){
toBeReplaced.push(currentNumber-9);
}
}
/*East*/
if((currentNumber+1) > 0 && (currentNumber+1) < maxValue){
if($("#"+(currentNumber+1)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber+1)) == -1){
toBeReplaced.push(currentNumber+1);
}
}
/*South East*/
if((currentNumber+11) > 0 && (currentNumber+11) < maxValue){
if($("#"+(currentNumber+11)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber+11)) == -1){
toBeReplaced.push(currentNumber+11);
}
}
/*South*/
if((currentNumber+10) > 0 && (currentNumber+10) < maxValue){
if($("#"+(currentNumber+10)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber+10)) == -1){
toBeReplaced.push(currentNumber+10);
}
}
/*South West*/
if((currentNumber+9) > 0 && (currentNumber+9) < maxValue){
if($("#"+(currentNumber+9)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber+9)) == -1){
toBeReplaced.push(currentNumber+9);
}
}
/*West*/
if((currentNumber-1) > 0 && (currentNumber-1) < maxValue){
if($("#"+(currentNumber-1)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber-1)) == -1){
toBeReplaced.push(currentNumber-1);
}
}
/*North West*/
if((currentNumber-11) > 0 && (currentNumber-11) < maxValue){
if($("#"+(currentNumber-11)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber-11)) == -1){
toBeReplaced.push(currentNumber-11);
}
}
if(livingCell){
if(check == 0 || check == 1 ){
if(toRemoveClass.indexOf(currentNumber) == -1){
toRemoveClass.push(currentNumber);
}
}
if(check == 4 || check == 5 || check == 6 || check == 7 || check == 8 ){
if(toRemoveClass.indexOf(currentNumber) == -1){
toRemoveClass.push(currentNumber);
}
}
if(check == 2 || check == 3){
if(toAddClass.indexOf(currentNumber) == -1){
toAddClass.push(currentNumber);
}
}
} else {
if(check == 3){
if(toAddClass.indexOf(currentNumber) == -1){
toAddClass.push(currentNumber);
}
}
}
}
checkAgain(toBeReplaced);
}
for(var i=0; i<toRemoveClass.length; i++){
$("#"+toRemoveClass[i]).removeClass("valid");
}
for(var i=0; i<toAddClass.length; i++){
$("#"+toAddClass[i]).addClass("valid");
}
toBeReplaced = toAddClass;
if(toAddClass.length == 0){
//exit
return;
} else {
setInterval(function(){
gol($.unique(toBeReplaced));
},1000);
}
selectedCells = [];
toAddClass =[];
toRemoveClass = [];
};
start = function(){
if(selectedCells.length == 0){
alert("select cell");
} else {
gol(selectedCells);
}
};
});
})();
body{
background: #BBDEFB ;
}
td {
width: 20px;
height: 20px;
background: #eee;
}
table {
cursor: default;
}
.valid {
background: #00BFA5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>Conways Game of Life</title>
<link rel="stylesheet" type="text/css" href="gameOfLife.css">
</head>
<body>
<h1><code>Conway's game of life</code></h1>
<div id="container">
<h2><code>enter row * columns</code></h2>
<form>
<code>row ★ column : </code>
<input id="rowNo" type="text"/> ★
<input id="columnNo" type="text"/>
</form>
<button id="submit"> Submit </button>
<br><br>
</div>
<table class="table"></table>
<br><br>
<button onClick="start()"> start </button>
<br><br>
<h2><code> Rules </code></h2>
<code>1. Any live cell with fewer than two live neighbours dies,
as if caused by underpopulation.</code><br>
<code>2. Any live cell with more than three live neighbours dies,
as if by overcrowding.</code><br>
<code>3. Any live cell with two or three live neighbours lives
on to the next generation.</code><br>
<code>4. Any dead cell with exactly three live neighbours becomes
a live cell.</code>
<script type="text/javascript" src="gameOfLife.js"></script>
</body>
</html>
Without digging really deep into your code. You build the IDs by using col and row index, so you'll get something like 11, 12, 13, 14, 15, ... 110, 111, 112 etc. for the first row. Without a delimiter the ID of the eleventh row first element would be 111 too. As soon as you use a kind of delimiter like '_' your IDs are unique: 1_1, 1_2 again.
for(var row=1; row<=noOfRow; row++){
for(var col=1; col<=noOfColumn; col++){
column += "<td id =" + inc+"_"+col + "> </td>";
/* you also could add data attributes:
data-row=\""+row+"\" data-col=\""+col+"\"
*/
}
appendRow += "<tr>"+column+"</tr>";
column= "";
inc++;
}
Looking into your code, I think you will get other problems, because there is a lot of code related to "10". For example: if((currentNumber-9) > 0 && (currentNumber-9) < maxValue){ - this won't work in case you'll have more than 9 rows. But fixing this would be a rewritten version of the complete game.

Looping in Javascript array

I have a simple quesetion and I'm not sure why the array content is not being returned properly. I'm pretty sure this is something simple but somehow I'm not getting the results I want. The scenario is that a variable "compare" is set to a value e.g. "apple" and I am looping into the array, and, if apple matches an index print that into the text field. It doesn't do it and it always says the "not the same" value. For value dog it works. It seems like it reaches the last array then does comparisons. Help please.
Code below
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
var text = "";
var i;
var arr = ["apple", "banana", "carrot", "dog"];
var compare = "apple";
for (i = 0; i < arr.length; i++) {
if (arr[i] == compare) {text = "The value is " + arr[i] + "<br>"; }
else if (compare == "" || compare == null) { text = "The value is blank"; }
else if (arr[i] != compare) {text = "not the same"; }
else {text ="some error";}
}
document.getElementById("demo").innerHTML = text;
}
</script>
<p>Click the button to do a loop with a break.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
function print(msg) {
document.getElementById("demo").innerHTML += msg + '</br>';
}
function myFunction() {
var text = "";
var i;
var arr = ["apple", "banana", "carrot", "dog"];
var compare = document.getElementById('compare').value;
if (!compare) {
print('Compare is empty');
return;
} else {
print('Comparing with ' + compare);
}
for (i = 0; i < arr.length; i++) {
if (arr[i] == compare) {
print("The value is at index " + i + " is " + arr[i]);
return; //results found, break out of the for loop
} else if (arr[i] != compare) {
print("not the same");
} else {
print("some error");
}
}
print("Could not find " + compare + " in array");
}
<!DOCTYPE html>
<html>
<body>
<script>
</script>
<p>Click the button to do a loop with a break.</p>
<input type="text" id="compare" placeholder="Compare to" />
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
For performance reasons it is better to validate the value of compare before the loop starts. You can break out of the loop using break, continue or return keywords.
It seems like it reaches the last array then does comparisons. Help please.
In effect, yes, because you never stop the loop. So all of the previous assignments you've done to document.getElementById("demo").innerHTML are overwritten by the final one.
If you want to stop when you find a match, use break to break out of the loop.
If you want the element to have a list of what had happened (which I think might be what you were trying to do, it's hard to tell), build the list up in text and then assign at the end:
if (compare == "" || compare == null) {
// Doesn't make sense to loop in this case, presumably
text = "The value is blank";
} else {
text = "";
for (i = 0; i < arr.length; i++) {
if (arr[i] == compare) {
text += "The value matches " + arr[i] + "<br>";
// ^--- note the +=
} else {
text += "The value doesn't match " + arr[i] + "<br>";
// ^--- note the +=
}
}
}
document.getElementById("demo").innerHTML = text;
You never break the for loop. You must use break; to exit the loop when the if condition is met.
Here your is your solution: http://jsfiddle.net/urahara/rvLyfsto/
and your code:
function myFunction() {
var text = "";
var i;
var arr = ["apple", "banana", "carrot", "dog"];
var compare = "apple";
for (i = 0; i < arr.length; i++) {
if (arr[i] == compare) {
text = "The value is " + arr[i] + "<br>";
break;
} else if (compare == "" || compare == null) {
text = "The value is blank";
break;
} else if (arr[i] != compare) {
text = "not the same";
break;
} else {
text = "some error";
break;
}
}
document.getElementById("demo").innerHTML = text;
}
Cheers!

Categories