how do i replace chunks of a character with a single character

Viewed 38

So I have a string something like this

thing thing2 thing3 thing4

How do I replace the chunks of spaces with a single character, so the output would be

thing|thing2|thing3|thing4

The chunks are random length

2 Answers

You can use the regular expression \s+ to match one or more consecutive whitespace characters and replace them with pipes.

const str = 'thing       thing2    thing3         thing4';
const res = str.replace(/\s+/g, '|');
console.log(res);

You use the string replace() method:

var s = 'thing       thing2    thing3         thing4'
s = s.replace(/ +/g, '|');
console.info(s);

Related