Mr. Jo
Mr. Jo

Reputation: 5271

Concatenate / simplify RegExp

I've this working RegExp in my JavaScript file:

var reA = new RegExp(urlValueToRemove);
var reB = new RegExp('(,&)');
var reC = new RegExp('(,,)');
var reD = new RegExp('(=,)');
var reE = new RegExp('(,$)');

window.history.pushState(null, null, decodeURIComponent(window.location.search).replace(reA, '').replace(reB, '&').replace(reC, ',').replace(reD, '=').replace(reE, ''));

Is it possible to concatenate / simplify this so that I don't need to do the replace 5 times?

I've asked this in the codereview community but there is nobody available so I think I must need to wait days there.

Example

When I have this URL here:

http://localhost.com/?color=Red,Blue,Green&size=X,L,M,S

When I want to remove now the Green from the URL I can pass Green to the first Regex reA and it gets removed from the URL:

http://localhost.com/?color=Red,Blue&size=X,L,M,S

Upvotes: 2

Views: 76

Answers (1)

trincot
trincot

Reputation: 350770

You can use the capture group to indicate what should be kept, and join the two cases with a |: one case needs to keep the character that precedes the word (like =), the other what follows the word (like &):

function removeWord(url, text) {
    const re = new RegExp(`,${text}(&|,|$)|(=)${text},`, 'g');
    return url.replace(re, '$1$2');
}

const url = "http://localhost.com/?color=Red,Blue,Green&size=X,L,M,S"
console.log(removeWord(url, "Green"));

Upvotes: 2

Related Questions