Search code examples
javascriptregexspecial-charactersstr-replace

javascript - remove extra spaces before given characters


I have this function, which adds an extra spaces after comma.

 function fixString1(inp){
    var i, len, arr, outp, Rside, Lside, RsideIsNum, LsideIsNum;

    arr = inp.split(",");
    outp = "";

    for(i=1, len=arr.length; i<len; i++){
        Lside = arr[i-1];
        Rside = arr[i];

        LsideIsNum = /\d/.test(Lside.charAt(Lside.length-1));
        RsideIsNum = /\d/.test(Rside.charAt(0));

        outp += "," + ((LsideIsNum && RsideIsNum)?"":" ") + Rside;
    }

    return (arr[0] + outp).replace(/ {2,}/g, " ");
}

How can it modify to apply more than one character, I mean I want to apply this function besides comma to . ! ? : chars too.

Anyone know how to solve?


Solution

  • Add one more parameter to the function declaration which indicates the character. If you want to run the function only once then you can provide a set of the characters in the split function e.g. inp.split(".,'")