How to replace the first matching string in vueJS?

Hi Friends 👋,

Welcome To SortoutCode! ❤️

Today I am going to show you How do you replace the first matching of a string in VueJS.

This tutorial will help you to replace the same strings or words from your string data. we will see two methods to replace all occurrences in a string.

Now we are going to replace using the below methods

Table of content

  • Define Content for test from replace() method
  • Javascript replace() method
  • Javascript replace with regex global method

Let’s start the today’s tutorial How do I replace the first matching of a string in VueJS?

Define Content for test from replace() method

Let’s define the Content in the data of the FirstComponent.vue component for testing purposes.

<script>
export default {
    name: 'FirstComponent',
    data() {
        return{
            longstring: "Hi Friends an an Welcome To SortoutCode!",
            result:'',
        }
    },
}
</script>

Data is used to define properties in a particular component. In a single-file component, data() is a function that returns a set of properties that have been defined in the function.

In the above code long string is the property that returns the "Hi Friends an an Welcome To SortoutCode!" content.

Javascript replaceAll() method

The replace() method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

it also does not work in older node.js versions.

<template>
    <div>
        <div>
            <h3>"{{longstring}}"</h3>
            <h3>All the word 'an' is replaced with 'very' word: </h3><h1>{{result}}</h1>
        </div>
    </div>
</template>

<script>
export default {
    name: 'FirstComponent',
    data() {
        return{
            longstring: "Hi Friends an an Welcome To SortoutCode!",
            result:'',
        }
    },
    mounted(){
        const occurance = this.longstring.replace('an', 'very');
        this.result = occurance;

    }
}
</script>

For now, let’s check the output.

Output

ReplaceAll Method

All the best 👍.

Follow me on Twitter