character-replacement

Regular Expressions in Javascript erasing spaces


JAVASCRIPT REGULAR EXPRESSIONS

This code searches for single quotation marks and replaces them with double quotation marks. It will not replace a single quotation mark that is part of a word (i.e. don't)

function testRegExp(str)
{
    var matchedStr = str.replace(/\W'|'\W/gi, '"');
    return matchedStr;
}
console.log(testRegExp("I'm in a 'blue house with a cat' and I don't care!"))

RESULT --->I'm in a"blue house with a cat"and I don't care!

Notice there are no spaces were the double quotation marks replace the single quotation marks. Why did the space disappear before and after this quotation? Thanks


Solution

  • /\W'|'\W/gi
    

    You are replacing any non-word character followed by a single quote (\W') or (|) any single quote followed by a non-word character ('\W) with a double quote without any spaces.

    Spaces count as non-word characters, so you are basically replacing the space and single quote with a double quote without spacing.

    Here is a solution for your problem:

    function testRegExp(str)
    {
        var matchedStr = str.replace(/\W'/g, ' "').replace(/'\W/g, '" ');
        return matchedStr;
    }
    
    console.log(testRegExp("I'm in a 'blue house with a cat' and I don't care!"))