Home > Software engineering >  Ignore punctuation from counting on a textfield
Ignore punctuation from counting on a textfield

Time:06-23

I have put a length validator in a textfield but I want to ignore punctuation from counting.

What I have is this:

  <v-text-field v-model="note" maxlength="255" dense>
          </v-text-field>

What I have tried is replacing the punctuation with empty string:

 watch: {
  note(val) {
   if (val) {
   this.note = val.replace(/[.,/#!$%^&*;:{}=-_`~()]/g, "")
  }
 }
}

But it doesn't work..

CodePudding user response:

There are two things :

  • One is to replace the punctuations with an empty string from the input value (This is what you are trying to do in your code).
  • Second is that you just want to ignore the count of the punctuations but don't want to replace them. (I think this is what you want ?)

Here is the live demo as per the second statement (For demo purpose I just put default maxlength as 20) :

new Vue({
  el: '#app',
  data: {
    note: null,
    noteMaxLength: 20
  },
  watch: {
    note() {
        this.noteMaxLength = 20;
      const val = this.note.replace(/[.,/#!$%^&*;:{}=_`~()]/g, "");
      this.noteMaxLength = this.noteMaxLength   (this.note.length - val.length);
      console.log('count', this.noteMaxLength);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="text" v-model="note" :maxlength="noteMaxLength"/>
</div>

CodePudding user response:

try the below regex in replace code.

/[^ \w] /g

CodePudding user response:

You can exclude alphanumeric characters and spaces characters to get this

/[^\w\s] /g

Which works like

  • ^ #Exclude following.

  • \w #Word characters.

  • \s #Space characters.

  • Related