Home > Enterprise >  Not to match with regex in angular if there are any attachments, letters, words at the beginning and
Not to match with regex in angular if there are any attachments, letters, words at the beginning and

Time:08-17

Update Question;

First of all hi everyone, i'm new here, i will try hard to get my question right.

how the data came to me;

    0: {highWord: 'hafif ticari araçlarda', color: '#00FF00'}
    1: {highWord: 'hafif ticari', color: '#00FF00'}
    2: {highWord: 'kamyon', color: '#00FFFF'}
    3: {highWord: 'MAN', color: '#00FFFF'}
    4: {highWord: 'otobüs', color: '#00FFFF'}
    5: {highWord: 'AĞIR VASITA', color: '#00FFFF'}
    6: {highWord: 'ağır vasıta', color: '#00FFFF'}
    7: {highWord: 'Ağır vasıta', color: '#00FFFF'}
    8: {highWord: 'Ağır Vasıta', color: '#00FFFF'}

here is the code block where I match my words;

 let searchRgx = new RegExp(this.highlightWordList.map(item => {
      console.log(item)
      return item.highWord;
    }).join("|"), 'gi');

this is the output this code gives me

/hafif ticari araçlarda|hafif ticari|kamyon|MAN|otobüs|AĞIR VASITA|ağır vasıta|Ağır vasıta|Ağır Vasıta/gi

and I paint the matched word here but it matches wrong

 let _this = this
  return txt.replace(searchRgx, function (match, offset, string)  {
     
      let foundedKeyword = _this.highlightWordList.filter(item => {
        return item.highWord.toLowerCase() === match.toLowerCase();
      })[0];

      if (foundedKeyword == undefined) {
        foundedKeyword = {};
        foundedKeyword.color = 'white';
      }


      return `<span style='background-color:${foundedKeyword.color};' >${match}</span>`;
    });

for example: when i write "lookman" my code above also matches the "man" in the word "lookman"

what I want is that when I type "lookman" it doesn't match "man".

I hope I asked the right question (with the rules) thanks in advance

CodePudding user response:

Expanding on the comment from kelly

You can add word boundries \b. Updating the line where you're generating the regex

let searchRgx = new RegExp(this.highlightWordList.map(item => {
    console.log(item)       
    return '\\b('   item.highWord   ')\\b'; 
    // Another string formatting option:  `\\b(${item.highWord})\\b`    
}).join("|"), 'gi');
  • Related