For example:
\'abcjkjokabckjk\'.replace(\'/(abc)/g\',...)
If I want to replace a specify position \'abc\', what I can do?
Like this
This can be done without RegEx.
String methods String#indexOf, String#lastIndexOf can be used with String#substring
var string = 'abcde|abcde|abcde|abcde',
needle = 'abc',
firstIndex = string.indexOf(needle),
lastIndex = string.lastIndexOf(needle);
// ----------------------------------------------------------------
// Remove first occurence
var first = string.substring(0, firstIndex) + '***' + string.substring(firstIndex + needle.length);
document.getElementById('first').innerHTML = first;
// ----------------------------------------------------------------
// Remove last occurence
var last = string.substring(0, lastIndex) + '***' + string.substring(lastIndex + needle.length);
document.getElementById('last').innerHTML = last;
// ----------------------------------------------------------------
// Remove nth occurence
// For Demo: Remove 2nd occurence
var counter = 2, // zero-based index
nThIndex = 0;
if (counter > 0) {
while (counter--) {
// Get the index of the next occurence
nThIndex = string.indexOf(needle, nThIndex + needle.length);
}
// Here `nThIndex` will be the index of the nth occurence
}
var second = string.substring(0, nThIndex) + '***' + string.substring(nThIndex + needle.length);
document.getElementById('second').innerHTML = second;
table tr td:nth-child(2) {
color: green;
}
td {
padding: 15px;
}
After replacing first occurence:
After replacing last occurence:
After replacing 2ndzero-based index occurence: