-1

I'm trying to convert numbers to words by JavaScript. My code:

function NumbersToWords(number) {
    var numbersArray = [1, 2, 3, 4, 5];
    var wordsArray = ["one", "two", "three", "four", "five"];
    for (let i = 0; i <= numbersArray.length; i++) {
        number = number.toString().replace(numbersArray[i], wordsArray[i]);
    };
    return number;
};
console.log(NumbersToWords(122));

When I convert "122", return "onetwo2" instead of "onetwotwo". Is there any problems in my code? Thanks

dphuc23
  • 63
  • 5
  • 1
    You should loop your `number` characters, not `wordsArray`. That's why it only translates once – Justinas Jun 30 '21 at 07:05
  • `.replace();` only replaces the first instance found. You can use `.replaceAll()` – VLAZ Jun 30 '21 at 07:05
  • [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+replace+only+replaces+first+occurrence) of [How to replace all occurrences of a string in JavaScript](/q/1144783/4642212). – Sebastian Simon Jul 02 '21 at 03:25

3 Answers3

6

The replace, replaces the first occurance of the string. You don't need the '<=' btw, '<' is enough.

function NumbersToWords(number) {
  var numbersArray = [1, 2, 3, 4, 5];
  var wordsArray = ["one", "two", "three", "four", "five"];
  for (let i = 0; i < numbersArray.length; i++) {
    number = number.toString().replaceAll(numbersArray[i], wordsArray[i]);
  }
  return number;
}
console.log(NumbersToWords(122));
console.log(NumbersToWords(1224));
Moataz Alsayed
  • 381
  • 2
  • 12
0

The reason it won't work, is because replace according to the docs, "If pattern is a string, only the first occurrence will be replaced."

Alternatively, you could map your numbers Array to words.

function NumbersToWords(number) {
    var numbersArray = [1, 2, 3, 4, 5];
    var wordsArray = ["one", "two", "three", "four", "five"];
        number = number.toString().split('').map( (i,index) => {
         return wordsArray[i-1]
        })
    return number.join('');
};
FMa
  • 88
  • 7
0

An alternative approach might be to map over the numbers:

const numbersArray = [1, 2, 3, 4, 5];
const wordsArray = ['one', 'two', 'three', 'four', 'five'];

function NumbersToWords(number) {
  return number

    // Coerce the number to a string
    .toString()

    // Into an array
    .split('')

    // Create a new array of mapped strings
    .map(el => wordsArray[el - 1])

    // Join the array into a string again
    .join('');
};

console.log(NumbersToWords(122));
Andy
  • 61,948
  • 13
  • 68
  • 95