0

My program has the following line where I am replacing parts of a string with another.

for('condition'){    
Searched_in_Text_Mod = Searched_in_Text_Mod.replace(new RegExp('\\b'+split_search_key+'\\b','g')," ");
}

The code works well so long as there are no special characters.

Wherever split_search_key has any special characters, the replace action terminates as follows: (Logger output and Execution transcript)

[18-06-16 13:22:14:832 IST] Sat Jun 16 13:22:14 GMT+05:30 2018
[18-06-16 13:22:15:609 IST] regex = /\bGrass .*& .*Plastic .* .* .*(Brown .*& .*Pink)\b/
[18-06-16 13:22:15:610 IST] Searched_in_Text =  Meghalaya Grass & Plastic   (Brown & Pink)
[18-06-16 13:22:15:610 IST] 11.0
[18-06-16 13:22:15:610 IST] Searched_in_Text_Mod =  Meghalaya Grass & Plastic   (Brown & Pink)
[18-06-16 13:22:15:611 IST] split_search_key = Grass
[18-06-16 13:22:15:611 IST] Searched_in_Text_Mod =  Meghalaya   & Plastic   (Brown & Pink)
[18-06-16 13:22:15:612 IST] split_search_key = &
[18-06-16 13:22:15:612 IST] Searched_in_Text_Mod =  Meghalaya   & Plastic   (Brown & Pink)
[18-06-16 13:22:15:613 IST] split_search_key = Plastic
[18-06-16 13:22:15:613 IST] Searched_in_Text_Mod =  Meghalaya   &     (Brown & Pink)
[18-06-16 13:22:15:614 IST] split_search_key = 
[18-06-16 13:22:15:614 IST] Searched_in_Text_Mod =   Meghalaya    &     ( Brown  &  Pink )
[18-06-16 13:22:15:615 IST] split_search_key = 
[18-06-16 13:22:15:615 IST] Searched_in_Text_Mod =    Meghalaya     &     (  Brown   &   Pink  )
[18-06-16 13:22:15:616 IST] split_search_key = (Brown



[18-06-16 13:22:15:615 IST] Logger.log([split_search_key = , []]) [0 seconds]
[18-06-16 13:22:15:616 IST] Logger.log([Searched_in_Text_Mod =    Meghalaya     &     (  Brown   &   Pink  ), []]) [0 seconds]
[18-06-16 13:22:15:616 IST] Logger.log([split_search_key = (Brown, []]) [0 seconds]
[18-06-16 13:22:15:668 IST] Execution failed: SyntaxError: Unterminated parenthetical . (line 49, file "Code") [0.786 seconds total runtime]

I realise its got to do with the regex. But am not able to solve it myself. Help will be greatly appreciated.

Sujeeth

Sujeeth
  • 11
  • 2
  • `new RegExp('\\b'+split_search_key.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')+'\\b','g')` – Wiktor Stribiżew Jun 16 '18 at 08:01
  • Wiktor Stribiżew: I will follow your advise to solve this. Thanks – Sujeeth Jun 16 '18 at 08:26
  • Wiktor, Could you please help me understand why the RegexSearch Key "/\bWash\+\b/i" does not find a match within "Wash\+ Formula" ?? [18-06-16 12:21:58:848 PDT] regex = /\bWash\+\b/i [18-06-16 12:21:58:849 PDT] -1.0 [18-06-16 12:21:58:850 PDT] 1. Searched_in_Text = Wash\+ Formula – Sujeeth Jun 16 '18 at 19:23
  • Because there is no word boundary between `+` and a space. Use `.replace(new RegExp('(^|\\W)('+split_search_key.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')+')(?!\\w)','g'),"$1 ")` if you have non-alphanumeric chars in the search_keys. – Wiktor Stribiżew Jun 16 '18 at 21:18

0 Answers0