JavaScript: Using Regex Pattern Match to Remove Repeated Character from End of String: replace(), regex
s
is a string object which uses dot notation to access the replace()
method. That method has two parameters: 1. regex pattern; 2. replacement string.
Remove Redundancy
Since a conventional greeting is suited to general correspondence, excessive characters can be removed from the exuberant greeting "Hi!!!!!"
in Node.js REPL:
$ sudo node
> const remove = s => s.replace(/!+$/, "")
> console.log(remove("Hi!!!!!"))
Hi
Cryptic Regex
Regular expressions, aka regex patterns, can become cryptically exasperating, since they can be riddled with specialized characters. Or overwhelming, depending upon how large they become. The simple regular expression /!+$/
is enclosed within forward slashes, / /
. The textual character !
will be matched. The special character +
matches its preceding textual character multiple times. And would remove all matched textual characters if it was not for the special character $
which restricts that removal to characters located at the end of string s
only. But while the effect is removal, in reality, each "!"
was replaced with ""
or an empty string.