简体   繁体   中英

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

The problem lies with mapping the data.split(' ') . Notice that when you call that on a string username { username} scrypt secret {password} you will not get an array with 5 elements, as you would like (ie ['username', '{ username}', 'scrypt', 'secret', '{password}'] ), but it will split on every space character; so the resulting array looks more like this:

[
  'username',   '',
  '{',          '',
  '',           'username}',
  'scrypt',     'secret',
  '{password}'
]

If you can, I would advice on making the arr array as an array of arrays, each subarray consisting of words you want to launch a regex through. If this is, however, not an option, I would suggest not splitting like that, but mapping like this:

this.mappedArr = this.arr.map(data => {
    const editable = data.match('([{].*?[}])');
    console.log(editable);
    return {
      editable,
      data: !editable ? 
            data :
            data.match(/(\{+ *)?\w+( *\}+)?/g).map(word => ({word, editable: word.match('^[{].*?[}]$')})) <
    };
})

This begs for refactoring though, but it should work as an emergency fix.

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,'')+' ')
    })
  }

在此处输入图片说明

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,'') + ' ')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM