Search code examples
javascriptregexregular-language

Replace all dots to single


How to replace

. . . Hello . . . . . . world . . .

to

. Hello . world .

replace "point space point" by simply point

Tried it like this:

/(\.\s\.)+/i

Solution

  • We can phrase the replacement as being any single dot, which in turn is followed by a space and another dot, that entire quantity occurring one or more times. That is, we can find on the following pattern and then replace with just a single dot:

    \.( \.)+
    

    Code sample:

    var input = ". . . Hello . . . . . . world . . .";
    console.log(input);
    input = input.replace(/\.( \.)+/g, ".");
    console.log(input);

    Edit:

    We could make the pattern slightly more efficient by turning off capturing using ?:, i.e. use the following pattern:

    \.(?: \.)+