How to replace all occurrences of a string in vueJS?

Hi Friends đź‘‹,

Welcome To SortoutCode! ❤️

Today I am going to show you How do you replace all occurrences 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 replaceAll() method
  • Javascript replaceAll() method
  • Javascript replace with regex global method

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

Define Content for test from replaceAll() 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 above code long string is the property that returns the "Hi Friends an an Welcome To SortoutCode!" content.

Javascript replaceAll() method

The replaceAll() 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.replaceAll('an', 'very');
        this.result = occurance;

    }
}
</script>

For now, let’s check the output.

Output

ReplaceAll Method

All the best đź‘Ť.

Follow me on Twitter