javascriptreplacems-wordimacros

How to replace the break with a comma after two words?


I use the following line of code to replace all spaces with commas between words.

SET keyword-virgula EVAL("var spatiu=\"{{Keyword}}\"; spatiu.replace(/ /g,','); ")

How could I make the comma be added after two words?

word word, word word, word word, word word, word word,

Can someone help me? thanks

I am using: Browser: Google Chrome Version 105.0.5195.102 (Official Build) (64-bit)

iMacros Personal Edition License - Addon for Chrome -Version 10.1.1

Windows 10 (64-bit)


Solution

  • You can match 2 times one or more non whitespace characters followed by 1+ whitespace character in between using a pattern.

    In the replacement use the full match using $& followed by a comma.

    const s = "word word word word word word word word word word";
    const regex = /\S+\s+\S+/g
    console.log(s.replace(regex, "$&,"));