Search code examples
javascriptregexangularangular7

regex match starts and ends with expression using angular


I have my working example here

https://stackblitz.com/edit/angular-fk2vpr?embed=1&file=src/app/app.component.ts

here I wrote condition like if word starts and ends with { and } they need to highlight and in editable way. here its working fine for word which is having no space like {username} but in case of { host} then its not taking that word to highlight and also if somewords like {pas}!!

then word of {pas} alone needs to highlight but its taking along with that !!

Can anyone assist me what mistake I made on this scenario

Thanks in advance


Solution

  • Try with below code it will work.

     const editable = data.match(/{+.*?}+/gi);
      if(editable){
        editable.map(word => {
          const re= new RegExp(word,'g');
          data = data.replace(re,' '+ word.replace(/\s/gi,'')+' ')
        })
      }
    

    enter image description here

    As per above code the token {username}!! will not work as we are splitting with space. To resolve that problem we can do add extra space before and after of that token. Use below line to work in all condition.

    data = data.replace(word, ' ' + word.replace(/\s/g,'') + ' ')