So, I have a function which has two params: string and match index to replace and i need to replace only match with that index. How can i do that?
Example:>
You need to use the function parameter of the replace function, and also maintain an index (i
) of matches.
function replaceAt(string, replaceThis, replaceWith, at) {
let i = 0;
if (Array.isArray(at)) {
return string.replace(replaceThis, (match, offset) => at.includes(i++) ? replaceWith : match)
} else if (Number.isInteger(at)) {
return string.replace(replaceThis, (match, offset) => i++ === at ? replaceWith : match)
} else {
return string;
}
}
// usage:
console.log(replaceAt("aaaaabcde", /a/g, ".", [2, 0])); // ".a.aaabcde"
console.log(replaceAt("aaaaabcde", /a/g, ".", 2)); // "aa.aabcde"
String.prototype.replaceAt = function(replaceThis, replaceWith, at) {
let string = this, i = 0;
if (Array.isArray(at)) { // e.g. console.log("aaaaabcde".replaceAt(/a/g, ".", 2)); => "aa.bcde"
return string.replace(replaceThis, (match, offset) => at.includes(offset) ? replaceWith : match)
} else if (Number.isInteger(at)) { //e.g. console.log("aaaaabcde".replaceAt(/a/g, ".", [2, 0])); => ".a.bcde"
return string.replace(replaceThis, (match, offset) => offset === at ? replaceWith : match)
} else {
return string;
}
}
// usage:
console.log("aaaaabcde".replaceAt(/a/g, ".", [2, 0])); // ".a.aaabcde"
console.log("aaaaabcde".replaceAt(/a/g, ".", 2)); // "aa.aabcde"
function replaceExceptAt(string, replaceThis, replaceWith, at) {
let i = 0;
if (Array.isArray(at)) { // e.g. console.log(replaceExceptAt("aaaaabcde", /a/g, ".", 2); => "..a..bcde"
return string.replace(replaceThis, (match, offset) => !at.includes(i++) ? replaceWith : match)
} else if (Number.isInteger(at)) { //e.g. console.log(replaceExceptAt("aaaaabcde", /a/g, ".", [2, 0])); => "a.a..bcde"
return string.replace(replaceThis, (match, offset) => i++ !== at ? replaceWith : match)
} else {
return string;
}
}
// usage:
console.log(replaceExceptAt("aaaaabcde", /a/g, ".", [2, 0])); // "a.a..bcde"
console.log(replaceExceptAt("aaaaabcde", /a/g, ".", 2)); // "..a..bcde"
String.prototype.replaceExceptAt = function(replaceThis, replaceWith, at) {
let string = this, i = 0;
if (Array.isArray(at)) { // e.g. console.log("aaaaabcde".replaceExceptAt(/a/g, ".", 2); => "..a..bcde"
//return string.replace(replaceThis, (match, offset) => !at.includes(offset) ? replaceWith : match)
return string.replace(replaceThis, (match, offset) => !at.includes(i++) ? replaceWith : match)
} else if (Number.isInteger(at)) { //e.g. console.log(replaceAt("aaaaabcde", /a/g, ".", [2, 0])); => "a.a..bcde"
return string.replace(replaceThis, (match, offset) => i++ !== at ? replaceWith : match)
} else {
return string;
}
}
// usage:
console.log("aaaaabcde".replaceExceptAt(/a/g, ".", [2, 0])); // "a.a..bcde"
console.log("aaaaabcde".replaceExceptAt(/a/g, ".", 2)); // "..a..bcde"