1

Im trying to add asterisks at the beginning and end of each word but I keep getting undefined at the end of my new string. Thanks for the help in advance.

function solution(s) {
var asterisks = "*"
var newString = ""
for(let i = 0; i <= s.length; i++){
    if(s === ""){
        return "*";
    }else{
    newString += asterisks + s[i];} 
}
return newString;
}

1
  • for example if were to log solution("star"), I would get "starundefined" But what I want is "*star*" Commented Nov 16, 2022 at 3:31

2 Answers 2

2

I think your for loop should be

for(let i = 0; i < s.length; i++)

Cause in the last time of your for loop, i = s.length.

And s[s.length] = undefined

Sign up to request clarification or add additional context in comments.

Comments

0

Your issue is for(let i = 0; i <= s.length; i++) the <= should just be < the undefined is coming from the last "length" character not existing.

You can get around adding the final * and the end of the last letter by add this code to the for loop:

if (i == (s.length -1)){
    return newString += asterisks;
    }

Working example:

function solution(s) {
var asterisks = "*"
var newString = ""
for(let i = 0; i < s.length; i++){
    if(s === ""){
        return "*";
    }else{
    newString += asterisks + s[i];} 
    
    if (i == (s.length -1)){
    return newString += asterisks;
    }
}
return newString;
}

document.getElementById("test").innerHTML = solution('hello');
<div id="test"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.