charAt() not working second time in function for javascript

charAt() not working second time in function for javascript


function translateWord(n)
for (var i = 0; i < n.length; i++)
if( n.charAt(i).toLowerCase() == "a")
return n.charAt(i) = "alpha ";





im trying to translate the letter at "i" into alpha but whenever i add the charAt(i) statement it just stops working?



note: im trying to translate the letter at "i" into alpha, not check if it is alpha



for example if i was to write 'aa' i want it to come out as 'alpha alpha'





return n.charAt(i) = "alpha "; Invalid syntax - = is assignment.
– CertainPerformance
Aug 31 at 6:57


return n.charAt(i) = "alpha ";


=





return n.charAt(i) == "alpha "; SInlge = is assignment == equality check
– Manos Kounelakis
Aug 31 at 7:00





Also charAt returns a char not a string.Why would you compare a char with a string
– Manos Kounelakis
Aug 31 at 7:01





What do you want to do? Assignment statement with return clause is an invalid clause...
– codeLover
Aug 31 at 7:02





Syntax error aside, the return statement would also break out of the loop. So n.charAt(i) would only get called once. There's a lot of errors in just 3 lines of code.
– Claus Jørgensen
Aug 31 at 7:13


n.charAt(i)




3 Answers
3



How by doing something like this:




var mystring = "amazon";
mystring = mystring.split('a').join('alpha');
console.log(mystring);





it worked, thank you ^-^
– xaegi
Aug 31 at 7:46





@xaegi Happy to help. Best of luck!
– Karan Dhir
Aug 31 at 7:58



Simple use String.replace()


String.replace()




function translateWord(n)
return n.replace('a','alpha');


console.log(translateWord('man'));



Method 1)




function translateWord(str, word, newWord)

var len = 0, newStr = '';

while (len < str.length)
newStr += ( str.charAt(len).toLowerCase() === word ) ? newWord : str[len];
len++;


return newStr;



console.log(translateWord('Amazon','a','alpha'));



Method 2)




function translateWord(str)
return str.replace(/a/gi,'alpha');


console.log(translateWord('Amazon'));



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Some of your past answers have not been well-received, and you're in danger of being blocked from answering.



Please pay close attention to the following guidance:



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)