Wednesday, July 22, 2020

A robust search and replace, using regular expression (I think*)

This is a robust implementation of https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace

function myReplace(str, before, after) {
    return str.replace(
        new RegExp(`(?<=\\s|,)${escapeRegExp(before)}(?!\\w)`, 'gi'), 
              x => (x[0] === x[0].toUpperCase() ? after[0].toUpperCase() : after[0]) + after.slice(1)
              // this would work too:
              // x => after[0][`to${x[0] === x[0].toUpperCase() ? 'Upper' : 'Lower'}Case`]() + after.slice(1)
    );
}

// bobince's version
function escapeRegExp(string) {
    return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}


const source = `The net profit of ASP.NET is nice. It's a money-magnet platform
A good safety net. Net is what spider-man makes. .NET is nice
.NET is super cool
The netizens are correct. .net, .NET are all the same thing
Some basket,net,basketball net,toys
This a good Net I would say
That is a good net
Net satisfaction is at all-time high
Good net!`;
 
console.log(myReplace(source, "net", "gross"));   
console.log();
console.log(myReplace(source, ".NET", "_DOT_NET_")); 
console.log();
console.log(myReplace(source, "ASP.NET", "ASP Classic"));   

Output:
The gross profit of ASP.NET is nice. It's a money-magnet platform
A good safety gross. Gross is what spider-man makes. .NET is nice
.NET is super cool
The netizens are correct. .net, .NET are all the same thing
Some basket,gross,basketball gross,toys
This a good Gross I would say
That is a good gross
Gross satisfaction is at all-time high
Good gross!

The net profit of ASP.NET is nice. It's a money-magnet platform
A good safety net. Net is what spider-man makes. _DOT_NET_ is nice
_DOT_NET_ is super cool
The netizens are correct. _DOT_NET_, _DOT_NET_ are all the same thing
Some basket,net,basketball net,toys
This a good Net I would say
That is a good net
Net satisfaction is at all-time high
Good net!

The net profit of ASP Classic is nice. It's a money-magnet platform
A good safety net. Net is what spider-man makes. .NET is nice
.NET is super cool
The netizens are correct. .net, .NET are all the same thing
Some basket,net,basketball net,toys
This a good Net I would say
That is a good net
Net satisfaction is at all-time high
Good net!

No comments:

Post a Comment