photosynthesis_bro
photosynthesis_bro

Reputation: 81

Why I can't substitute vowel with space in a string?

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.

Upvotes: 0

Views: 57

Answers (4)

Cid
Cid

Reputation: 15247

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

Upvotes: 2

zb22
zb22

Reputation: 3231

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()

Upvotes: 0

gobinda
gobinda

Reputation: 124

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.

Upvotes: 0

KooiInc
KooiInc

Reputation: 122916

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

Upvotes: 2

Related Questions