serial index replace

In this example below you will see how to do a serial index replace with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by refactorized, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright refactorized ©
  • HTML
  • CSS
  • JavaScript
    <input id="pattern" type="text"></input>

<textarea id="in">
</textarea>

<textarea id="out">
</textarea>



/*Downloaded from https://www.codeseek.co/refactorized/serial-index-replace-qmygzx */
    textarea{
  width: 100%;
  min-height: 40vh;
}


/*Downloaded from https://www.codeseek.co/refactorized/serial-index-replace-qmygzx */
    const makeRgx = pat => {
  console.log(pat)
  let esc = pat.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
  console.log(esc)
  return RegExp(esc,'g')
}

const serialNum = ( pad = 2, i = 0, pre = '', post = '') => () => {
  let arr = Array(pad).fill(0)
  let digits = (i + '').split('')
  let len = digits.length
  i++
  arr.splice(-len, len, ...digits)
  return `${pre}${arr.join('')}${post}`
}

const serialfy = (str, pat, pre='', post='') => {
    if(pat && pat.length) {
    let sn = serialNum(3, 0, pre, post)
    let rgx = makeRgx(pat)
    return str.replace(rgx, sn)  
  }
  return str
}




$(()=>{
  const onChange = (e) => {
    let input = $('#in').val()
    let pat = $('#pattern').val()
    $('#out').val(serialfy(input, pat, 'k'))
  }
  $('#in').change(onChange)
  $('#pattern').change(onChange)
})

let testStr = "hello, here's a serial: xxx, here's another: xxx, and some more: xxx, xxx, xxx, xxx, and xxx"
console.log(serialfy(testStr, 'xxx', 'a'))


Comments