xaegi
xaegi

Reputation: 11

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'

Upvotes: 1

Views: 74

Answers (3)

Ehsan
Ehsan

Reputation: 12959

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'));

Upvotes: 0

Karan Singh Dhir
Karan Singh Dhir

Reputation: 751

How by doing something like this:

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

Upvotes: 1

prasanth
prasanth

Reputation: 22500

Simple use String.replace()

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

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

Upvotes: 1

Related Questions