[Vuejs]-How to remove space between string after paste it in vue2

1👍

You should use watchers for this:

data()
{
  return {
    first_input: '',
    second_input: '',
  }
},
watch:
{
  first_input()
  {
    this.$nextTick(() =>
    {
      this.first_input = this.first_input.replace(/\s+/g, '');
    })
  },
  second_input()
  {
    this.$nextTick(() =>
    {
      this.second_input = this.second_input.replace(/\s+/g, '');
    })
  },
}

2👍

I was able to get the behavior I think you requested, where you can paste in a string with tailing whitespace, and it will be trimmed. The trick is to prevent the browser from doing anything after the paste using event.preventDefault() and using main_text.trim() to remove whitespace. Please let me know if this is what you’re looking for.

(Tested on Google Chrome 91, using this codesandbox)

<template>
  <span>
    <input class="form-control inputHeight"
        @keydown.space.prevent
        @paste.space="remove_on_paste"
        v-model="floatingData.from_id">
    <input class="form-control inputHeight"
        @keydown.space.prevent
        @paste.space="remove_on_paste"
        v-model="floatingData.to_id">
  </span>
</template>

<script>
export default {
  data() {
    return {
      floatingData: {
        from_id: "",
        to_id: ""
      }
    }
  },
  
  methods: {
    // Remove space on paste
    remove_on_paste(event) {
      let main_text = event.clipboardData.getData("text");

      event.preventDefault();
      this.floatingData.from_id = main_text.trim();
    }
  }
};
</script>

Leave a comment