0
var rec = "Hello world is the best line ever.";
rec = rec.toLowerCase();

for(var i=0;i<rec.length;i++){
    if(rec[i] === 'a' || rec[i] === 'e' || rec[i] === 'i' || rec[i] === 'o' || rec[i] === 'u'){
    rec[i] = " ";
  }
}
console.log(rec);

I learned that we can approach strings the same way we manipulate array in Javascript, at least in this case I believe this should work properly but for some reason I get the whole string in output. To emphasize, I just need string rec without vowels, instead with (or without) space.

  • 1
    Does this answer your question? [How do I replace a character at a particular index in JavaScript?](https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript) – Ivar Nov 07 '20 at 11:56
  • 2
    because, primitives, such as strings, are immutable – Jaromanda X Nov 07 '20 at 11:56
  • 4
    Strings are immutable, so they can't be changed in-place like an array. Instead, you can consider building a _new_ string – Nick Parsons Nov 07 '20 at 11:57

4 Answers4

2

There are many ways to achieve this, but to keep with your own way, few changes are needed.

Strings are immutable. If you want to modify one, you may want to use an array of words instead, that you'll join into a sentence later.

The spread operator helps doing that : [...str]

var rec = "Hello world is the best line ever.";
rec = [...rec.toLowerCase()]; // transform it as an array

for(var i=0;i<rec.length;i++){
    if(rec[i] === 'a' || rec[i] === 'e' || rec[i] === 'i' || rec[i] === 'o' || rec[i] === 'u'){
    rec[i] = " ";
  }
}
rec = rec.join(''); // rebuild a string using join() method
console.log(rec);
lacrit
  • 115
  • 5
Cid
  • 14,968
  • 4
  • 30
  • 45
2

The string can not be mutated (it is immutable). You can replace the vowels using a regular expression though:

const rec = "Hello world is the best line ever.".replace(/[aeiou]/gi, " ");
console.log(rec);
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • This is probably the best approach, even for someone not comfortable with RegEx – Cid Nov 07 '20 at 12:07
0

as the others said, strings are immutable but you can get a new string with the output you want using String.prototype.replace() and String.prototype.charAt():

rec.replace(rec.charAt(i)), ' ')

You can also use String.prototype.replaceAll() to replace all the occurrences of the vowel characters with regex:

const regex = [aeiou]/g;
rec.replaceAll(regex,' '); 

String.prototype.charAt()
String.prototype.replace()
String.prototype.replaceAll()

zb22
  • 3,126
  • 3
  • 19
  • 34
0

Because in javascript string is immutable.

So,

rec[i] = " "; --> this wont work as expected,

Instead,

rec = rec.substring(0, i) + ' ' + rec.substring(i+1);

This line generates new string 'rec' object with replaced character in it.

gobinda
  • 124
  • 3