[Vuejs]-Vue.js โ€“ How to add html tag in the starting of string when match found

2๐Ÿ‘

โœ…

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>

1๐Ÿ‘

what you need is string.replace("sometag","<sometag>") instead of substring.indexOf(string)

๐Ÿ‘คHeshamSalama

0๐Ÿ‘

let given_string = "hey this is StackOverflow" , search = "flow", my_tag = "Tag" , tagged = "";

if(given_string.indexOf(search) !== -1)
  {
    let splited = given_string.split(search);
    splited.forEach(item => {
      if(item !== "")
        {
          tagged += item + " " + "<"+ my_tag +">" + search + "</"+ my_tag +">";
        }
    })
    
    
    
  }

console.log(tagged);
๐Ÿ‘คsazzad

Leave a comment