locutus
Version:
Locutus other languages' standard libraries to JavaScript for fun and educational purposes
23 lines (22 loc) • 1.05 kB
JavaScript
const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
export function replacingOccurrences(str, target, replacement, caseInsensitive = false) {
// discuss at: https://locutus.io/swift/String/replacingOccurrences/
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Replaces every occurrence of target in str, similar to Swift replacingOccurrences(of:with:options:).
// example 1: replacingOccurrences('hello world', 'l', 'L')
// returns 1: 'heLLo worLd'
// example 2: replacingOccurrences('Swift swift SWIFT', 'swift', 'ts', true)
// returns 2: 'ts ts ts'
// example 3: replacingOccurrences('abcabc', 'ab', '#')
// returns 3: '#c#c'
const source = String(str);
const needle = String(target);
const nextValue = String(replacement);
if (needle === '') {
return source;
}
if (caseInsensitive) {
return source.replace(new RegExp(escapeRegExp(needle), 'gi'), nextValue);
}
return source.replaceAll(needle, nextValue);
}