Regex to replace multiple spaces with a single space

后端 未结 23 2666
北恋
北恋 2020-11-22 10:00

Given a string like:

\"The dog      has a long   tail, and it     is RED!\"

What kind of jQuery or JavaScript magic can be used to keep spaces to only o

23条回答
  •  借酒劲吻你
    2020-11-22 10:28

    I know we have to use regex, but during an interview, I was asked to do WITHOUT USING REGEX.

    @slightlytyler helped me in coming with the below approach.

    const testStr = "I   LOVE    STACKOVERFLOW   LOL";
    
    const removeSpaces = str  => {
      const chars = str.split('');
      const nextChars = chars.reduce(
        (acc, c) => {
          if (c === ' ') {
            const lastChar = acc[acc.length - 1];
            if (lastChar === ' ') {
              return acc;
            }
          }
          return [...acc, c];
        },
        [],
      );
      const nextStr = nextChars.join('');
      return nextStr
    };
    
    console.log(removeSpaces(testStr));

提交回复
热议问题