Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Find the first occurrence of particular word in a given string using Vue.js filters

  • Last Updated : 31 Mar, 2021

In this article, we are going to learn how to find the first occurrence of a particular word in a given string using filters in VueJS. Vue is a progressive framework for building user interfaces. 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 first occurrence of a particular word can be found out by applying a filter to the required string. We will use the JavaScript indexOf() method to check the index of the first occurrence of the word. If the word has an exact match, then the corresponding index is returned and if the word is not found then ‘-1’ is returned as the index.

Example:

index.html




<html>
<head>
  <script src=
  </script>
</head>
<body>
  <h1 style="color: green;">
    GeeksforGeeks
  </h1>
  <div id='parent'>
    <p>{{st1}}: <strong>
        Index: {{ st1 | find('portal') }}
      </strong></p>
  
    <p>{{st2}}: <strong>
        Index: {{ st2 | find('programming') }}
      </strong></p>
  
    <p>{{st3}}: <strong>
        Index: {{ st3 | find('React') }}
      </strong></p>
  </div>
  <script src='app.js'></script>
</body>
</html>

app.js




const parent = new Vue({
  el: "#parent",
  data: {
    st1: "GeekforGeeks is a computer science portal",
    st2: "C++ is a best language for competative programming",
    st3: "Javascript is best for scripting",
  },
  
  filters: {
    find: function (st, target) {
      const idx = st.indexOf(target);
      return idx;
    },
  },
});

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!