Reputation:
I'm trying to loop through a string, where on every comma found in the string I want to do something; until there are no more comma's left.
I know there is a better way to actually do this searching for regex until you reach the end of the string, but cant remember (and my googling skills are lacking today), so if you could share this knowledge it would be appreciated. However, an answer as to why this code snippet throws the error in the title would also be appreciated, so I can avoid it in the future. :)
function CtorToCaller()
// This functions intention is to format the string representation of a classes Ctor into a
string representation of the caller used to insatiate the class.
{
var input = document.getElementById("input").value;
input = input.replace(/(\r\n|\n|\r|[;]|[:])/gm," ");
input = input.trim();
var myClass = input.slice(0, input.search(" "));
input = input.slice(input.search(/[(]/) + 1, input.search(/[)]/)) //Cut the parameters out of string
while(input.search(",") > 0)
{
let myindex = input.search(); //Error here.
let param = input.slice(0, myindex);
let input = input.slice(myindex+ 1, input.length());
console.log(param);
console.log(input);
}
document.getElementById("output").innerHTML = '"new ' + myClass + input + '",';
}
I'm obviously missing a the logic within the while loop to complete the functions purpose. I don't believe it should be pertinent to the issue at hand, but ask if you need more info.
Upvotes: 0
Views: 1041
Reputation: 943480
let myindex = input.search(); //Error here. let param = input.slice(0, myindex); let input = input.slice(myindex+ 1, input.length());
Your code is trying to access the variable defined on line 3 of the extract above on line 1 … which is two lines before it exists.
You probably intended to access the other variable you also named input
and defined outside the while
loop but you have shadowed it and now can't.
Use unique names for variables. Use a linter with a rule like eslint's no-shadow to detect this kind of problem automatically.
Upvotes: 1