How to use regex in vueJS?
June 06, 2022Hi Friends đź‘‹,
Welcome To SortoutCode! ❤️
Today I am going to show you How do you use Regular expressions ( regex ) in VueJS.
This tutorial will help you to use Regular expressions ( regex ) in VueJS, here we will learn below three points in VueJS regex.
Table of Content
- Define Content for the test from regex
- Regex to get true or false
- Regex to get match value
- Regex to get no of occurrence match value
Let’s start the today’s tutorial How do I use Regular expressions ( regex ) in VueJS?
Define Content for the test from regex
Let’s define the Content in the data of the FirstComponent.vue
component for testing purposes.
<script>
export default {
name: 'FirstComponent',
data() {
return{
items: "Hi Friends Welcome To SortoutCode!",
}
},
}
</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 items
is the property that returns the "Hi Friends Welcome To SortoutCode!"
content.
Regex to get true or false
We have the .test()
method, it will return true when the string matches or false if not.
<template>
<div>
<div>
<h3>"{{items}}"</h3>
<h3>regex matches "SortoutCode" strings from content, true or false: </h3><h1>{{result}}</h1>
</div>
</div>
</template>
<script>
export default {
name: 'FirstComponent',
data() {
return{
items: "Hi Friends Welcome To SortoutCode!",
result:'',
}
},
mounted(){
const regex = /SortoutCode/;
const matches = regex.test(this.items);
this.result = matches;
}
}
</script>
For now, let’s check the output.
Output
All the best 👍.