0

the replace function isnt working as a thought it would. came across this piece of code. i know the replace function is to replace all punctuation marks so as to not count them as letters. but when i log a string including punctuations it counts them as well. trying to figure out why

const getLetterCount = (stringToTest) => {
  const wordArray = stringToTest.split('');
  let totalLetters = 0;
  for (let word of wordArray) {
    word.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
    totalLetters += word.length;
  }
  console.log(totalLetters);
}

getLetterCount('boy/girl?')  // returns 9 ( counting punctuation as well)
Douwe de Haan
  • 6,247
  • 1
  • 30
  • 45
  • Strings are immutable (meaning once declared, they cant be changed again). So [`String#replace`](https://developer.cdn.mozilla.net/de/docs/Web/JavaScript/Reference/Global_Objects/String/replace) returns a copy of the original string after the replacements have happened. Just rewrite the function to `function getLetterCount (stringToTest) { return stringToTest.replace(/[.,\/#!$%\^&\*;:{}=\-_\`~()]/g, "").length;}` – nick zoum Aug 10 '20 at 12:30
  • 3
    This function is completely buggy. But more importantly, the bug is that `.replace()` returns a new string, with replacement. so you need `word = word.replace`. – Derlin Aug 10 '20 at 12:31
  • 1
    also splitting a string by an empty string(instead of a space) results in an array containing each individual letter. – LJᛃ Aug 10 '20 at 12:31
  • ``return stringToTest.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "").length``? – Ivar Aug 10 '20 at 12:53
  • @nickzoum thats a much simple way of getting it done. thank you! – tony baidoo Aug 10 '20 at 12:57

1 Answers1

3

String.prototype.replace()

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

You have to reassign the new value to the variable (word).

const getLetterCount = (stringToTest) => {
  const wordArray = stringToTest.split('');
  let totalLetters = 0;
  for (let word of wordArray) {
    word = word.replace(/[.,\/#!$%\^&\*;:{}=\-_` ~()]/g, "");
    totalLetters += word.length;
  }
 console.log(totalLetters);
}

getLetterCount('boy/girl?')  // returns 9 ( counting punctuation as well)
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • I think it's important to state in the answer, that strings are immutable (so no operation can alter their content). I would also include a shorter version of the function (without removing the on you have) since all it really needs is `.replace(/.../g, "").length`. (Upvoted) – nick zoum Aug 10 '20 at 13:01