Is there an infinite loop in my code? - javascript

My webpage crashes when I run this:
function replace()
{
var str = document.getElementById('feeds');
var cont = str.innerHTML;
curstring = "twitter: ";
while (cont.indexOf(curstring))
{
replaced = cont.replace(curstring,"TWIMG ");
str.innerHTML = replaced;
}
}

Yes, when curstring is in cont. In your while loop cont won't be changed, so cont.indexOf(curstring) will always be true.

Probably, yes.
Your cont.indexOf() test should test for >= 0, since on not-found that function returns -1, which evaluates true and will cause the loop to go around again.
It'll currently only terminate if cont starts with curstring.
Per other answers, you also need to overwrite cont inside the loop too.
function replace() {
var curstring = "twitter: ";
var str = document.getElementById('feeds');
var cont = str.innerHTML;
var old = cont;
// NB: indexOf() returns -1 on failure, so you
// must compare against that,
while (cont.indexOf(curstring) >= 0) {
cont = cont.replace(curstring, "TWIMG ");
}
// taken outside the loop so we don't modify the DOM
// over and over if the match is repeated - only update
// the DOM if the string got changed
if (cont !== old) {
str.innerHTML = cont;
}
}

Yes there is. You never reassign cont. Perhaps try this?
function replace()
{
var str = document.getElementById('feeds');
var cont = str.innerHTML;
curstring = "twitter: ";
while (cont.indexOf(curstring) != -1)
{
replaced = cont.replace(curstring,"TWIMG ");
str.innerHTML = replaced;
cont = str.innerHTML;
}
}

Yes cont never changes in the loop so if cont.indexOf(curstring) is true it will be true forever and your program goes into an infinite loop.

Related

tried to repeating the double letter of any string.ex- "hello" --> 'hheelloo' but stucked at for loop, any solution?

function doubleChar(str) {
var splt = str.split("");
for(var i=0;i<splt.length-1;i++){
var rpt= splt[i].repeat(2);
return rpt.join('');
}
}
console.log("hello");
An Haskellesque approach here just for fun...
var str = "hello",
double = ([c,...cs]) => c ? cs.length ? c + c + double(cs) : c + c : "";
console.log(double(str));
There were few problems in your code :
function doubleChar(str) {
var splt = str.split("");
for(var i=0;i<splt.length-1;i++){
var rpt= splt[i].repeat(2);
return rpt.join('');
}
}
console.log("hello");
first is that the code prints string "Hello" no matter what function doubleChar does.
in order to make console.log print result of doubleChar function you need to change it to this
console.log(doubleChar("Hello"))
now your code would call doubleChar function with the string "Hello" as input of function doubleChar and print the output of the function.
Now in your function, the return should not be inside of the loop, when the return is inside the loop, function sends the result of first iteration and there would be no other iterations
function doubleChar(str) {
var splt = str.split("");
for(var i=0;i<splt.length-1;i++){
var rpt= splt[i].repeat(2);
}
return rpt.join('');
}
console.log(doubleChar("hello"));
.join('') is for arrays when you want to mix all elements into a string but rpt is not an array but a string so you can just return rpt itself :
function doubleChar(str) {
var splt = str.split("");
for(var i=0;i<splt.length-1;i++){
var rpt= splt[i].repeat(2);
}
return rpt
}
console.log(doubleChar("hello"));
you also should not use var inside the loop because by doing so the javascript redefines the rpt and all previous values are lost so you can declare variable outside the loop and append new values inside the loop
function doubleChar(str) {
var splt = str.split("");
var rpt=''
for(var i=0;i<splt.length-1;i++){
rpt += splt[i].repeat(2);
}
return rpt
}
console.log(doubleChar("hello"));
now as final fix, inside your loop you're using i<splt.length-1 this probably because length is one more than maximum index but considering that you are using < instead of <= this is already taken care of. so your final code looks like :
function doubleChar(str) {
var splt = str.split("");
var rpt=''
for(var i=0;i<splt.length;i++){
rpt += splt[i].repeat(2);
}
return rpt
}
console.log(doubleChar("hello"));
The big problem I see here is that rpt is within the loop. So, the for loop will return "hh", then "ee", so on so forth. In practice, the function stops after returning a value so this would currently return 'hh'. To solve this, you need to move the variable outside of the for loop. Something like this:
var result = ""
for(var i=0;i<splt.length-1;i++){
result = result + splt[i] + splt[i]
}
return result;
Then you could console.log the result.
Answers above/below a great and correct. However, I'd like to answer using almost exactly the same code as in the question as it may be more helpful if you've just started learning JS.
You get "join is not a function" error because .repeat(n) returns a string and strings do not have such a method.
Then, you need to stop return inside of a loop as it actually returns from the whole function so you will only get the first letter doubled as a result. Instead, declare variable for storing result and concat it with a new doubled letter in loop. Return result in the end.
Here is the modified code:
function doubleChar(str) {
var splt = str.split("");
var result = ""; // add the var for future result
for(var i=0; i<splt.length; i++){
var rpt = splt[i].repeat(2); // this is string!
result += rpt; // concat string to current result
}
return result;
}
console.log(doubleChar("hello"));
The value of rpt is a string, and does not have a join function. You also immediately return inside the for loop, which will do that in the first iteration.
You can split, map and join instead:
const re = "hello".split('').map(s => s + s).join('');
console.log(re);
Your declaration of rpt is should be on the top, and the return should be outside your for loop. Other than that, its fine.
function doubleChar(str) {
var splt = str.split("");
var rpt = "";
for (var i = 0; i < splt.length; i++) {
rpt = rpt + splt[i].repeat(2);
}
return rpt;
}
console.log(doubleChar("hello"));
var rpt= splt[i].repeat(2);
return rpt.join('');
It is choking on this line because rpt is not an array and you're calling join() on it. Instead, just replace the original array item with the new double item.
function doubleChar(str) {
var splt = str.split("");
for(var i=0;i<splt.length-1;i++){
splt[i]= splt[i].repeat(2);
}
return splt.join('');
}
console.log(doubleChar("hello"));
all in one line...
str = "hello";
var dbl = str.split("").map(el => el.repeat(2)).join("")
console.log(dbl)
Now here is the same thing, but like your example, we'll only double up single letters
str = "hello", lastletter='';
var dbl = str.split("").map(el => {
if (el != lastletter) {
el = el.repeat(2)
lastletter = el.split("")[0]
return el
}
}).join("")
console.log(dbl)
I think most of the solutions here is hello->hheelllloo but you wanted like -> hheelloo
So assuming you only want to repeat single char. I'm giving the solution which also is the same code that you gave.
function doubleChar(str) {
var splt = str.split("");
var rpt="";
for(var i=0;i<splt.length;i++)
rpt+=((splt[i+1]&&splt[i]==splt[i+1]?splt[i++]:splt[i]).repeat(2));
return rpt;
}
console.log(doubleChar("hello"));
May be the line inside for loop seems complex but if you break this, it will be very simple
(splt[i+1]&&splt[i]==splt[i+1]) here I'm checking if the next char exist and equal to the current char, if so then take the current and skip the next char else take the current and don't skip the next char, and after this just repeating the char which we took.
rpt+=((splt[i+1]&&splt[i]==splt[i+1]?splt[i++]:splt[i]).repeat(2));
Hope you got this

Why Javascript console.log result is undefined while reversing the string?

var a = "gsdgtrshghf";
function reverseString(strr){
if (!strr.length){
var result="";
for(var i=strr.length;i>0;i++){
var a=strr.chatAt(i);
result+=a;
}
}return result;
}
console.log(reverseString(a))
When I tried to run it it returned me "undefined". I wonder what's the problem here.
The main reason is you are declaring var result="" and returning from outside of if(so it become undefined as its scope is only inside if statement) and other errors areas mention in comments you have a typo, charAt not chatAt. You can also simply use strr[i] to get the char. Also, you should do i-- and i >= 0 if you start at strr.length, otherwise for loop is immediately completed at the condition check. Check the below code.
var a = "gsdgtrshghf";
function reverseString(strr){
var result="";
if (strr.length){
for(var i=strr.length-1;i>=0;i--){
var a=strr.charAt(i);
result+=a;
}
}
return result;
}
console.log(reverseString(a))
Have a look:
var a = "gsdgtrshghf";
function reverseString(strr) {
var result = "";
if (strr.length != null) {
for (var i = strr.length - 1; i >= 0; i--) {
var a = strr.charAt(i);
result += a;
}
}
return result;
}
console.log(reverseString(a));
// Better
const reverse = str => Array.from(str).reverse().join('');
console.log(reverse('foo 𝌆 bar mañana mañana'));
Explanation
It's charAt(i) not chatAt(i)
Loop should start from length - 1 and end at 0 and i should be decremented
And finally declare the variable outside of if
i.e for(var i = strr.length - ; i >= 0; i--){
not for(var i=strr.length;i>0;i++){
Better yet, use combo of Array.from(str).reverse().join(''), as it even works with Unicode characters, as pointed out in comments by gaetanoM

Issue with my var getting undefined

I am trying to create a reverse function to the String type in javascript. My code is like
String.prototype.reverse = function () {
var s = "";
for(var i=this.length;i>=0;i--){
s+=this[i];
}
return s;
}
When I try to use it on for example like "test".reverse();
instead of giving "tset" it's giving "undefinedtset"
I am setting the variable like var s = ""; inside the function, still undefined is coming. Why is it so?
You just need to change var i=this.length to var i=this.length-1, because an array starts at position 0 :
String.prototype.reverse = function () {
var s = "";
for(var i=this.length-1;i>=0;i--){
s+=this[i];
}
return s;
}
this.length gives you 4 (4 letters in test word) and you start iterating from 4 to 0.
The problem is that nothing exists under 4 index (your letters are stored in 0-3 positions).
Try with:
for (var i = this.length - 1; i >= 0; i--) {
s += this[i];
}
The reason why your code isn't working has been answered by the others already, but if you want a shorter version of the reverse, you can do it like this:
String.prototype.reverse = function(){
return this.split('').reverse().join('');
}
console.log('Hello World'.reverse())

if else statement in while loop, where if else statement determines when while loop stops

var userInput = prompt("type something with or without double spacing");
var errorSpaces = [];
var maxSpaceCount = [];
var doneOnce = 0;
var done = 0;
var size;
var tempArray = [0, 0];
while (done === 0) {
if (doneOnce === 0) {
for (var i = 0; i<size; i++) {
size = userInput.length - 1;
if (userInput.substr(i, 2) == " ") {
userInput.replace(userInput.substring(i, j), userInput[i]);
errorSpaces.push(0);
}
}
doneOnce = 1;
maxSpaceCount.push(0);
} else if (doneOnce === 1 && tempArray.length != 1) {
for (var i = 0; i<size; i++) {
tempArray = [0];
size = userInput.length - 1;
if (userInput.substr(i, 2) == " ") {
userInput.replace(userInput.substring(i, j), userInput[i]);
tempArray.push(0);
}
doneOnce = 2;
}
maxSpaceCount.push(0);
} else {
done = 1;
}
}
alert("done");
This loops at the second for loop rather than finishing. I know it probably isn't the best way to do it, but how could I make the 'else if' work so that when there are no more double spaces, it will go to the final else?
I am trying to eliminate any multiple spaces by iteratively replacing double spaces with single spaces, then re-reading to replace further double (previously triple) spaces, etc.
Way , way too much code if your goal is to replace any double (or more spaces) with a single space
try regex
var userInput = prompt("type something with or without double spacing");
userInput = userInput.replace(/\s{2,}/g, ' ');
alert("done");
although not quite sure what you are trying to do with tempArray as it doesn't seem to make sense.
EDIT
There appears to be some indication that there is a requirement to count how many occurrences of 2 or more spaces, so using the below will give you the count. The reason for the || bit is because if none are found, it will return null, || [] will change the null to empty array, so the length of it will be zero. Thanks to #RobG
var countOfMultipleSpaces = (userInput.match(/\s{2,}/g) || []).length;
I'm sure it goes without saying that you have to do this before you replace them all
Is this what you want?
"type something with or without double spacing".replace(/\s{2,}/g, ' ');
//"type something with or without double spacing"

How to display the contents of an array after comma splitting it in Java Script

I am fairly new to Javascript and have been picking it up pretty quickly in the past few days, after staring at my code for hours and trying to figure out why it wasn't working the way I intended i figured i would post it here.
Anyways, so my question is how do I display the WHOLE content of an array after comma splitting it. My code is below. My code is only printing out the last number set that I input at the prompt.
Help would be highly appreciated.
var gradeinfo = new Object(); {
coursecode = new Array;
grade = new Array;
};
var changer = function (y) {
finalgradeinfo = new Array;
finalgradeinfo = y;
function newresults() {
var i = 0;
finalgradeinfo[i] = y;
i + 1;
}
return finalgradeinfo;
}
do {
var entry = prompt("Enter a course code and grade seperated by a comma");
if (entry != null && entry != "") {
var counter;
var entryvalid = new Array;
entryvalid = entry.split(",");
changer(entryvalid);
x = true;
} else {
x = false;
}
} while (x != false);
console.log(finalgradeinfo);
My function needs to include closure so if it looks entirely wrong i apologize in advance.
Help from this post
Split creates an array already. So, if you enter 1,2,3, you get an array like this when you split it: ["1", "2", "3"]. In your for loop, you are getting the characters from the original input, not your array. In order to add them, you need to change the input to numbers since they are considered strings. So your for loop should look like this:
for (i=0; i<3; i++)
{
entryArray[i] = parseFloat(entryArray[i]);
}
overwriting the strings with the digits.
In changer() you're destroying and recreating the array after each input. I suggest moving the array declaration into the global scope so that you can just push elements to it in the changer() function:
Fiddle
var finalgradeinfo = [];
var changer = function (y) {
finalgradeinfo.push(y);
}
do {
var entry = prompt("Enter a course code and grade seperated by a comma");
if (entry != null && entry != "") {
var counter;
var entryvalid = entry.split(",");
changer(entryvalid);
x = true;
} else {
x = false;
}
} while (x != false);
console.log(finalgradeinfo);
Notes:
Declaring arrays as [] is preferred to new Array
Not sure if you're aware but the newresults() function and gradeinfo object aren't doing anything
Also, the counter doesn't do anything, and the x boolean is unnecessary because it's basically just checking for prompt input. Here is my approach and fiddle.
var finalgradeinfo = { // declare finalgradeinfo in the global scope
coursecode: [],
grade: [] }
, entry = '';
do {
entry = prompt('Enter a course code and grade seperated by a comma') || ''; // will set entry to '' if user hits cancel
if (entry == '') continue; // break out of iteration if string is empty
var entryvalid = entry.split(",");
finalgradeinfo.coursecode.push(entryvalid[0]);
finalgradeinfo.grade.push(entryvalid[1]);
} while(entry !== '');
console.log(finalgradeinfo);

Categories