1.5 KiB
1.5 KiB
title, tags, expertise, author, cover, firstSeen, lastUpdated
| title | tags | expertise | author | cover | firstSeen | lastUpdated |
|---|---|---|---|---|---|---|
| Replace last occuerence in string | string,regexp | advanced | chalarangelo | blog_images/waves.jpg | 2021-04-22T09:01:22+03:00 | 2021-04-22T09:01:22+03:00 |
Replaces the last occurrence of a pattern in a string.
- Use
typeofto determine ifpatternis a string or a regular expression. - If the
patternis a string, use it as thematch. - Otherwise, use the
RegeExpconstructor to create a new regular expression using theRegExp.prototype.sourceof thepatternand adding the'g'flag to it. UseString.prototype.match()andArray.prototype.slice()to get the last match, if any. - Use
String.prototype.lastIndexOf()to find the last occurrence of the match in the string. - If a match is found, use
String.prototype.slice()and a template literal to replace the matching substring with the givenreplacement. - If no match is found, return the original string.
const replaceLast = (str, pattern, replacement) => {
const match =
typeof pattern === 'string'
? pattern
: (str.match(new RegExp(pattern.source, 'g')) || []).slice(-1)[0];
if (!match) return str;
const last = str.lastIndexOf(match);
return last !== -1
? `${str.slice(0, last)}${replacement}${str.slice(last + match.length)}`
: str;
};
replaceLast('abcabdef', 'ab', 'gg'); // 'abcggdef'
replaceLast('abcabdef', /ab/, 'gg'); // 'abcggdef'
replaceLast('abcabdef', 'ad', 'gg'); // 'abcabdef'
replaceLast('abcabdef', /ad/, 'gg'); // 'abcabdef'