javascriptvue.jsvuejs2vue-component

Vue.js - How to add html tag in the starting of string when match found


Suppose I have a string like this "hey this is StackOverflow" and my substring is "flow". While searching substring in the string it returns true using *indexOf*

What I want in this like when it matches the substring which is flow it appends the HTML tag in between this:

Example:

Input: "hey this is StackOverflow"

Output: "hey this is StackOver <'sometag'> flow <'/sometag'> "

The below code returns the true but didn't get any idea how to append the HTML tag in this.

substring.indexOf(string)

How can I achieve this?


Solution

  • Try string replace method :

    let str= "hey this is StackOverflow, flow"
    
    
    let newStr=str.replace(/flow/g,' <h1>flow</h1>')
    
    console.log(newStr)

    Then you could render it in the template using v-html directive like :

    Vue.config.devtools = false;
    Vue.config.productionTip = false;
    
    new Vue({
          el: '#app',
    
          data() {
            return {
              str: "hey this is StackOverflow"
            }
          },
    
          computed: {
            newStr() {
            return  this.str.replace(/flow/g, '<b>flow</b>')
            }
          }})
    <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
    
    
    <div id="app" class="container">
    
      <div v-html="str"></div>
      <div v-html="newStr"></div>
    </div>