Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace certain symbol in array?

Can you give me a hint what do I wrong trying to replace space symbol (' ') to ('-').

This is my code:

function hypernateAndLowerCase(strings)
{
  let newArray = [];
  for (let i = 0; i < strings.length; i++) { 
    if (strings[i].indexOf(' ')){
       strings[i].replace(' ', '-');

    }

    newArray.push(strings[i].toLowerCase());
  }
  return newArray;
}

console.log(hypernateAndLowerCase(['HELLO WORLD', 'HELLO YOU']));
like image 211
Елисей Горьков Avatar asked Dec 31 '25 04:12

Елисей Горьков


2 Answers

.replace does not mutate the original string - strings are immutable, so you'd have to explicitly assign the result of using replace for it to work. But, .map is more appropriate here, since you want to transform one array into another:

function hypernateAndLowerCase(strings) {
  return strings.map(string => string.replace(' ', '-').toLowerCase());
}

console.log(hypernateAndLowerCase(['HELLO WORLD', 'HELLO YOU']));

Note that passing a string to .replace will mean that, at most, only one occurrence will be replaced. If you want all occurrences to be replaced, use a global regular expression instead.

like image 51
CertainPerformance Avatar answered Jan 01 '26 20:01

CertainPerformance


You can simplify your function to following

function hypernateAndLowerCase(strings) {
  return strings.map(v => v.replace(/ /g, "-").toLowerCase());
}

console.log(hypernateAndLowerCase(['HELLO WORLD', 'HELLO YOU']));
like image 20
Nikhil Aggarwal Avatar answered Jan 01 '26 19:01

Nikhil Aggarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!