'Display only a part of the name if characters exceed a limit in Vue.js

I am trying to display a message once the user logs in.

In the case where number of characters exceed 8, how can I display only the first 8 characters of a name followed by ".." ? (Eg: Monalisa..)

new Vue({
    el: '#app',
    data: {
        username: 'AVERYLONGGGNAMMEEE'
    }
});

Here is my jsfiddle demo



Solution 1:[1]

Here is my answer fiddle : ANSWER-DEMO

<div id="app">
  <div v-if="username.length<8">Welcome, {{ username }}</div>
  <div v-else>Welcome, {{ username.substring(0,8)+".." }}</div>
</div>

Solution 2:[2]

UPDATE VUE 3

Filters have been removed from Vue 3.

With Vue3, you must use globalProperties if you want to be able to use a function in several components.

app.config.globalProperties.$filters = {
  str_limit(value, size) {
    if (!value) return '';
    value = value.toString();

    if (value.length <= size) {
      return value;
    }
    return value.substr(0, size) + '...';
  }
}

Use it like that:

{{ $filters.str_limit(8) }}

FOR VUE 2

You can also register a filter.

You can reuse the function simply in your project.

Vue.filter('str_limit', function (value, size) {
  if (!value) return '';
  value = value.toString();

  if (value.length <= size) {
    return value;
  }
  return value.substr(0, size) + '...';
});

Use it like that :

<div id="app">
  <div>Welcome, {{ username | str_limit(8) }}</div>
</div>

Solution 3:[3]

You can do this by using computed properties.

new Vue({
 el: '#app',
 data: {
  username: 'AVERYLONGGGNAMMEEE'
 },

 computed: {
   strippedUsername: function(){
      if(this.username.length > 5) {
         return this.username.slice(0,4);
      }
      return this.username;
   }
}


});

Solution 4:[4]

you want a computed property that check if the string is > 8 chars and make modifications and use that computed property in your template.

new Vue({
  el: '#app',
  data: {
    username: 'AVERYLONGGGNAMMEEE'
  },
  computed: {
    usernameLimited(){
      if ( this.username.length > 8 ) {
        return this.username.substring(0,8) + '...'
      } else {
        return this.username
      }
    }
  }
})

Solution 5:[5]

If you can do this with css, you should.

white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;

Solution 6:[6]

You can use substr() method to get part of the name:

var namePart = this.username.substr(0, 8) + '..';

Or you can use CSS overflow: hidden; and text-overflow: ellipsis; properties: demo.

Solution 7:[7]

Provide / Inject (Vue3)

In this solution I used the str_limit function presented above, but I decided to "serve" it to my component using Provide / Inject API.

The main idea is to have a separate file where all my injectable helper functions can be defined.

I started by creating a "providers" folder at the same level as my main.js and placing the following index.js inside of it. The idea was to have a dedicated place to define all my helper functions.

providers/index.js

const providers={
    strLimit: (value, size) => {
      
        if (!value) return '';
        value = value.toString();

        if (value.length <= size) {
            return value;
        }
        return value.substr(0, size) + '...';
    }
}

export default providers;

In this simplified App.vue, I import the provide method defined in providers/index.js into the app:

App.vue


 import providers from "./providers";

    export default {
      name:"App",
      data(){
        return {
        }
      },
      provide:providers
    }

In my main.js I create the vue app, pass the App.vue shown above and mount it:

main.js


import { createApp } from 'vue'
import App from "./App";

const app = createApp(App)
 app.mount('#app');
    app.config.errorHandler = (err) => {
       console.log(err);
    }

Now inside my component I inject the strLimit method:

component.vue

<template>
<h1>{{clip(title,20)}}</h1>

</template>
<script>

export default {
  name: "myComponent",
  inject:['strLimit'],
  data(){
    return {
      title:"This is a very long title, which should be clipped at around 20 characters"
    }
  },
  methods:{
    clip(text, length){
      return this.strLimit(text, length);
    }
  }
}
</script>

Solution 8:[8]

Think this way it can take care of one line. And checking for null values to avoid '[Vue warn]: Error in render: “TypeError: Cannot read property 'length' of null” with .substring()'

{{ username && username.length < 8 ? username : username.substring(0,8)+".."  }}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Ejaz Karim
Solution 4 mackmack
Solution 5 bbsimonbb
Solution 6 Sui Dream
Solution 7 thePHPHero
Solution 8