Skip to main content

What does the .trim modifier do?

The .trim modifier on the v-model directive automatically removes whitespace from the edges of a string before writing the value into the model.

Put simply:

.trim turns user input into a "clean" value with no leading or trailing spaces.


How does .trim work?

html
<input v-model.trim="username">

If the user types:

" Alex "

Then the username variable gets:

"Alex"

Vue does this automatically, with no extra code.


Example

html
<input v-model.trim="inputText"> <p>{{ inputText }}</p>

The user types:

" hello "

Result after input:

hello

When is .trim useful?

1. When entering logins, names, email

To remove accidental spaces:

" user@mail.com "

2. In form validation

To prevent situations where the user enters:

" " -> empty string -> error

Without .trim, such a string could be treated as non-empty.

3. For text without meaningful whitespace

For example:

  • titles
  • comments
  • search queries

4. To avoid bugs when comparing strings

For example:

js
if (username === "admin")

Without .trim, the comparison could be wrong because of spaces.


How does it work under the hood?

Vue automatically handles:

html
v-model.trim="value"

as:

  1. get event.target.value
  2. call .trim() on the string
  3. write the result into the model

That is:

js
value = event.target.value.trim();

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.