1

Following this question How can I strip all punctuation from a string in JavaScript using regex? I'm trying to remove all punctuation from a string besides the ' character to avoid messing with words such as:

  • wouldn't
  • don't
  • won't

So far I have tried the following:

return word.replace(/[^\w\s]|_\'/g, "")
          .replace(/\s+/g, " ");;

But it is still removing the ' character. Any idea how I can achieve such a result?

Bruno Francisco
  • 3,841
  • 4
  • 31
  • 61

2 Answers2

4

Move the escaped apostrophe to the excluded character class: /[^\w\s\']|_/g

Alien426
  • 1,097
  • 10
  • 12
0

Add the apostrophe to your regex like this, in the exclusion block:

const str = "This., -/is #! a ;: {} = - string$%^&* which `~)() doesn't, have any)( punctuation!";

const noPunctation = str.replace(/[^\w\s']|_/g, '').replace(/\s+/g, ' ');

console.log(noPunctation);
jo_va
  • 13,504
  • 3
  • 23
  • 47