-1

I want to format a string with not multiple space. String can have tab, carriage return or line feed.

Example 1: hello world expacted result: hello world

Example 2: hello world expected result : 'hello world'

const formatString = (s) => {
  const trimmed = s.trim();
  const formated = trimmed.match(/\s/g)
  return s.trim().replace(/\s+/g, ' ')
}

const str = `hello
world`
const result = formatString(str)
console.log(result)
xdeepakv
  • 7,835
  • 2
  • 22
  • 32
pradeepjan07
  • 29
  • 1
  • 3

1 Answers1

0

You can use space(exact sapce). easier

const formatString = (s) => {
  return s.replace(/ +/g, " ");
};

let str = `hello
world`;
const result = formatString(str);
console.log(result);
str = `hello    world`;

console.log(formatString(str));

Using regex:

const formatString = (s) => s.replace(/[^\S\r\n]+/g, " ");

console.log(
  formatString(`hello
world`)
);
console.log(formatString(`hello     world`));
xdeepakv
  • 7,835
  • 2
  • 22
  • 32