0

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

1 Answers1

0

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');
Quantum-Pie
  • 196
  • 7
  • I would like to ask one more question if you are available. //B character does not match Turkish characters, how can I fix it? For example;it matches when typed danış"man"ı but daniş"man" works correctly when typing @Quantum-pie – noNeedTagess Aug 17 '22 at 16:40
  • Not 100% sure I understand your question. But if you're expecting something like danışmanı to not match because of the ş character. You can update the regex to also check for specific Turkish characters, replace `\\b` with `[^a-zA-Zşı]` expanding as needed. Another option is `\\b` to `(?:\\s|^)(MAN)(?:\\s|$)` where \\s is white space and ^,$ are the start and end of the string – Quantum-Pie Aug 17 '22 at 22:28