skip to Main Content

I would like to remove spaces around hyphens in JS.

'Space - around - hypens' => 'Space-around-hypens'

I try the following, but it works only on the first hyphen:

str.replace(/s*-s*/, "-");

I also try this, but it throw an error that I don’t understand:

str.replaceAll(/s*-s*/, "-");

Uncaught TypeError: String.prototype.replaceAll called with a non-global RegExp argument

3

Answers


  1. Use the /g flag in the regex to indicate that it should be applied globally throughout the string.

    str.replaceAll(/s*-s*/g, "-");
    
    Login or Signup to reply.
  2. Originally, JavaScript didn’t have a replaceAll method, so to get the same effect as replaceAll through the replace method, we had to use regular expressions with it.

    Starting with ES12, you can use the replaceAll method added to String.prototype.

    When using it with a replaceAll regular expression, you still need to always use the g flag with it, otherwise you will get an error like TypeError: String.prototype.replaceAll called with a non-global RegExp argument.

    const str = '2023-12-27'
    const result1 = str.replaceAll('-', '') //20231227
    const result2 = str.replacAll(/-/, '') //error
    const result3 = str.replacAll(/-/g, '') //20231227
    
    
    Login or Signup to reply.
  3. const text = "This is a text- with - spaces around - hyphens.";
    const result = text.replace(/s*-s*/g, "-");
    console.log(result); // Output: "This-is-a-text-with-hyphens."
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search