I want java-script code to add custom button for find next and replace in summer-note editor like image given below -
I get success to replace text globally by using "gi" regex and also get success to replace all words one by one using "i" regex. But I am not able to skip word using find next and then replace next word.
Please help. Thanks in advance.
You can pass a function into your regex replace statement, in which you can replace only a certain nth match in the method shown here. When someone clicks Find Next
for the first time on a new search, it should create a variable to keep track of n
, setting it equal to 1 to start with. Each time they click Find Next
again, increase your value of n
. When they do click Replace
, call replaceNth
with that value, then increase the value of n
and move on to the next result.
The first call here shows that you can use this function as a catchall - if you don't pass n
, it will just replace everything. If you do pass n
, it will replace that one match.
function replaceNth(str, rgx, replacement, n){
if(n) {
let matchIndex = 0
return str.replace(rgx, match => {
return ++matchIndex == n ? replacement : match
})
} else {
return str.replace(rgx, replacement)
}
}
let sampleText = document.querySelector('p').textContent
console.log(replaceNth(sampleText, /cow/gi, 'MOO'))
console.log(replaceNth(sampleText, /cow/gi, 'MOO', 2))
<p>This is sample cow text with the word cow placed repeatedly cow within it.</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With