Truncate a String using filter in Vue.js

In this article, we are going to learn how to truncate strings using filters in VueJS. Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object. A single filter is a function that accepts a value and returns another value. The returned value is the one that’s actually printed in the Vue.js template.

The string extraction can be performed by applying a filter on the required string. There can be two approaches for writing the logic of the filter function:

Approach 1: In this approach, we use the JavaScript built-in methods split, slice and, join. The split method is used to split each character and convert them into a set of a character array. The slice method extracts the required portion of the string and returns it. The join method is used to convert an array of characters to a normal string. We will use all three methods together to truncate the string. The substr method can also be used to return a truncated string.

Example:

index.html




<html>
<head>
    <script src=
"https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js">
    </script>
</head>
<body>
    <div id='parent'>
        <p>
          <strong>Original String: </strong>
            {{st1}}
        </p>
  
        <p>
          <strong>Truncated String : </strong>
            {{ st1 | truncate(13) }}
        </p>
  
    </div>
    <script src='app.js'></script>
</body>
</html>


 

 

app.js




const parent = new Vue({
    el: '#parent',
    data: {
        st1: 'GeekforBeginner is a computer science portal'
    },
  
    filters: {
        truncate: function(data,num){
            const reqdString = 
              data.split("").slice(0, num).join("");
            return reqdString;
        }
    }
})


 

 

Output:

 

 

Approach 2: This method does not use any built-in JavaScript methods. The truncation is done by looping through the characters of the string for the required number of times and keep the required number of characters by appending them to the final string that would be returned.

 

index.html




<html>
<head>
    <script src=
"https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js">
    </script>
</head>
<body>
    <div id='parent'>
        <p>
          <strong>Original String: </strong>
            {{st1}}
        </p>
        <p><strong>Truncated String : </strong>
            {{ st1 | truncate(18) }}
        </p>
    </div>
    <script src='app.js'></script>
</body>
</html>


 

 

app.js




const parent = new Vue({
    el: '#parent',
    data: {
        st1: 'GeekforBeginner is a computer science portal'
    },
  
    filters: {
        truncate: function(data, num) {
            reqdString = ''
            for(let i=0; i<num; i++) {
                reqdString += data[i]
            }
            return reqdString;
        }
    }
})


 

 

Output: