JimF JimF - 1 month ago 7
Javascript Question

A regex for removing certain characters only if there is a space character on either side

I have a Javascript string:

var myString= "word = another : more new: one = two";


I am trying to figure out a regex that would produce this:

var myString= "word another more new: one two";


So when the pattern of a space followed by a = sign then followed by another space would result in the = sign being removed.

Likewise for the : character as well.

If the = character or the : character are removed that is fine or if those characters are replaced by a space character that is fine as well.

In summary to replace multiple occurrences of an = or a : if and only if they
surrounded by a space character.

Whichever regex is easier to write.

Answer Source

    //save the appropriate RegEx in the variable re
//It looks for a space followed by either a colon or equals sign
// followed by another space
    let re = /(\s(=|:)\s)/g;

//load test string into variable string
    let string = "word = another : more new: one = two";
//parse the string and replace any matches with a space
    let parsed_string = string.replace(re, " ");

//show result in the DOM
    document.body.textContent = string + " => " + parsed_string;