Avatar
Avatar

Reputation: 15156

Javascript Regex: How to remove all whitespaces around certain character?

Probably I am doing something wrong, I found a regex to achieve the needed replacement in PHP and in C#, but applying it to javascript fails.

Example:

text ( 4 |-4 | 1 "test" ) [ 0 50 90 ]

Should get cleaned to:

text(4|-4|1 "test")[0 50 90]

As you see, I remove all whitespaces before and after the brackets and the |.

My code so far:

        // remove whitespaces around brackets []
        text = text.replace(/\s*\[\s*(.*?)\s*]\s*/g, '[$1]');
        // remove whitespaces around brackets ()
        text = text.replace(/\s*\(\s*(.*?)\s*\)\s*/g, '($1)');
        // remove all whitespaces around | (FAILS)
        // text = text.replace(/\s*\|\s*(.*?)\s*\|\s*/g, '|$1|');
        // text = text.replace(/\s*|\s*/, '$1');

Looks also too complicated.

I would like to know the regex for each sign.

Not all replacements in one regex, for learning I would prefer one replacement per line.

Upvotes: 2

Views: 956

Answers (2)

Cerbrus
Cerbrus

Reputation: 72849

This will do the trick:

var text = 'text ( 4 |-4 | 1 "test"  )  [ 0 50 90 ]';
text = text.replace(/\s*([|()[\]])\s*/g, '$1');

alert(text)

This regex looks for (optional) whitespace, then, in a capature group, one of the characters that can't have bordering spaces, then another optional whitespace, and replaces all that with just the character, effectively removing the whitespace.


Now, if you want to place the replacements on seperate lines, and only replace space characters, leaving other whitespace intact, try this:

var text = 'text ( 4 |-4 | 1 "test"  )  [ 0 50 90 ]';
text = text.replace(/ *([|]) */g, '$1')
           .replace(/ *([(]) */g, '$1')
           .replace(/ *([)]) */g, '$1')
           .replace(/ *([[]) */g, '$1')
           .replace(/ *([\]]) */g, '$1');

alert(text)

Or this:

var text = 'text ( 4 |-4 | 1 "test"  )  [ 0 50 90 ]';
text = text.replace(/ *(|) */g, '$1')
           .replace(/ *(\() */g, '$1')
           .replace(/ *(\)) */g, '$1')
           .replace(/ *(\[) */g, '$1')
           .replace(/ *(\]) */g, '$1');

alert(text)

For single characters, character classes are a bit overkill, but you'll need to escape ()[], then. (Like I did in the last snippet)

Upvotes: 5

Rubens Farias
Rubens Farias

Reputation: 57936

The trick is to correctly escape the reserved chars, so a single [ becomes a \[ and so on. The pipe is also a reserved character, so you'll need to do the same:

var example = "text ( 4 |-4 | 1 \"test\"  )  [ 0 50 90 ]";
    example = example.replace(/\s*([\(\)])\s*/g, '$1')); // removes the ()
    example = example.replace(/\s*([\[\]])\s*/g, '$1')); // removes the []
    example = example.replace(/\s*([\|])\s*/g, '$1'));   // removes the |

    // or remove all characters at once
    example = example.replace(/\s*([\(\)\[\]\|])\s*/g, '$1')

alert(example)

Upvotes: 2

Related Questions