0

I am trying to add a comma when user type number or alphabetic. Actually, I applied regex for it and it working for number. When user type number it add comma to every input, but when I type alphabetic it does not work. Could someone please help me how to accept regex to accept both number and alphabetic.

Thanks

Regex

value.replace(/\B(?=(\d{1})+(?!\d))/g, ",");
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
Jonas
  • 261
  • 1
  • 3
  • 13

2 Answers2

2

UPDATE

If you want to insert a comma, every time you hit enter, just repair the commas using the following epxression:

/         BEGIN
(?<=\w)   POSITIVE LOOKBEHIND - PRECEDED BY WORD_CHAR
\b        WORD BOUNDARY
[\s,]*    ZERO OR MORE - WHITE_SPACE OR COMMA_CHAR
\b        WORD BOUNDARY
/         END
g         FLAGS = GLOBAL

const VK_ENTER = 13
const txt = document.querySelector('#sample-text')

const insertComma = (value) => value.replace(/(?<=\w)\b[\s,]*\b/g, ' , ')

const handleEnterKey = (e) => {
  var code = e.keyCode ? e.keyCode : e.which
  switch (code) {
    case VK_ENTER:
      txt.value = insertComma(txt.value)
      break
  }
}

document.addEventListener('keydown', handleEnterKey)
<form autocomplete="off" onsubmit="return false;">
  <input type="text" id="sample-text" value="" />
</form>

And now for something completely different…

Note: Original answer

You can listen for text input changes and swap the value by removing the present commas and re-adding them in the correct places.

For this example, if you type: "Hello 12345", the text will eventually become: "Hello 12,345"

const TYPE_AHEAD_DELAY = 0 // No delay
const SAMLE_TEXT = "Hello / 12345 / World"

let state = {
  sampleText: ''
}
  
const main = () => {
  state = createState(state) // Wrap the state in a proxy
  init()
  autoType('sampleText', SAMLE_TEXT, 250)
}

const processValue = (value, model) => {
  switch (model) {
    case 'sampleText':
      return fixCommas(value)
    default:
      return value
  }
}

const fixCommas = (value) => value
  .replace(/(\d),(\d)()/g, '$1$2')       // Revert commas
  .replace(/(\d)(?=(\d{3})+\b)/g, '$1,') // Add commas back

const autoType = (prop, value, timeout) => {
  let pos = 0, interval = setInterval(() => {
    state[prop] += value[pos++]
    if (pos >= value.length) {
      clearInterval(interval)
    }
  }, timeout)
}

/* #BEGIN BOILERPLATE */

const createState = (state) => {
  return new Proxy(state, {
    set(target, property, value) {
      target[property] = processValue(value, property)
      render(property)
      return true
    }
  })
}

const init = () => {
    Object.keys(state).forEach(property => {
    const input = document.querySelector(`[data-model="${property}"]`)
    let timeout
    input.addEventListener('keyup', (e) => {
      if (TYPE_AHEAD_DELAY) {
        if (timeout) clearTimeout(timeout)
        timeout = setTimeout(() => {
          listener(e)
        }, TYPE_AHEAD_DELAY)
      } else {
        listener(e)
      }
    })
  })
}

const listener = (event) => {
    const {type, value, dataset} = event.target
  state[dataset.model] = value
}

const render = (property) => {
  document.querySelector(`[data-model="${property}"]`).value = state[property]
}

main()
<input type="text" data-model="sampleText" />
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Thank you for answer , Actually I am using input what I want if user hit enter I want to add comma . For example if user type ( My ) and hit enter then I want to add comma . when user start type again and type ( Jonas ) it will add comma . Final result will be { My , Jonas ) . Could you please help me – Jonas Jul 16 '20 at 18:38
  • @Jonas so you just want to delimit what you just typed from what you are about to type after hitting enter? That seems completely different. – Mr. Polywhirl Jul 16 '20 at 18:43
  • Actually when user type something and hit enter I want to add comma . – Jonas Jul 16 '20 at 18:44
  • Thank you so much , Did you have any experience in redux form ? Actually I am trying to add keyDown listener but I am failed – Jonas Jul 16 '20 at 19:19
  • @Jonas since the event exists in the document, there is no need to query for components, just add the event when the component is mounted. See: https://stackoverflow.com/questions/41693715 – Mr. Polywhirl Jul 16 '20 at 20:34
1

You're matching any digit [0-9] with /d, if you change to any char it will work with any digit/letter.

Regex

"123abc".replace(/\B(?=(.{1})+(?!.))/g, ",");

var value = document.getElementById("original").innerText;

document.getElementById("modified").innerText = value.replace(/\B(?=(.{1})+(?!.))/g, ",");

var element = document.getElementById("inp");
element.addEventListener("keydown", function($event) {
  if($event.code === 'Enter'){
    $event.preventDefault();
    element.value += ","; 
  }
});
<span id="original">123abc</span>
<span id="modified"></span>

<input type="text" id="inp">
Nestor Perez
  • 827
  • 11
  • 17
  • @nester Thank you for answer , Actually I am using input what I want if user hit enter I want to add comma . For example if user type ( My ) and hit enter then I want to add comma . when user start type again and type ( Jonas ) it will add comma . Final result will be { My , Jonas ) . Could you please help me – Jonas Jul 16 '20 at 18:20
  • You should listen for keydown event on the input element, and when it detects the "enter" key, prevent the default behaviour and append a comma to the actual value. – Nestor Perez Jul 16 '20 at 18:25
  • Could you please edit your answer and write some simple example – Jonas Jul 16 '20 at 18:38
  • I think thats something different from what you ask for, but there you go. – Nestor Perez Jul 16 '20 at 18:55