Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find next and replace in summer-note editor using javascript

I want java-script code to add custom button for find next and replace in summer-note editor like image given below -

enter image description here

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.

like image 367
keerti Avatar asked Mar 19 '18 10:03

keerti


1 Answers

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>
like image 197
jmcgriz Avatar answered Sep 30 '22 12:09

jmcgriz