0

How can I prevent my "translator" from trying to replace, for example, the word keyboard like it was the words key and board and the word treehouse like it was tree and house?

I added some white spaces when calling the function to prevent it but what I need is to have something around the variable string when creating the RegExp so it checks for spaces without replacing them.

(function() {
  let variable = 'Something. Treehouse bla bla keyboard bla - The End';
  function replace(string, replacement) {
    const pattern = new RegExp(string, 'gi');
    variable = variable.replace(pattern, function(match) {
      if(match.charAt(0) === match.charAt(0).toLowerCase()) {
        return replacement;
      } else {
        return replacement.charAt(0).toUpperCase() + replacement.slice(1);
      }
    });
  }
  replace(' board', ' prancha');
  replace(' house', ' casa');
  replace('key ', 'chave ');
  replace('keyboard', 'teclado');
  replace('tree ', 'árvore ');
  replace('treehouse', 'casa na árvore');
  console.log(variable);
})();
user7393973
  • 2,270
  • 1
  • 20
  • 58
  • Or [Javascript reg ex to match whole word only, bound only by whitespace](http://stackoverflow.com/questions/2951915/javascript-reg-ex-to-match-whole-word-only-bound-only-by-whitespace). – Wiktor Stribiżew Mar 16 '17 at 09:58
  • I didn't noticed the name but thank you guy who told me to use `'\\b' + string + '\\b'`. I hadn't learned about that yet, I was thinking with `\w`, `\s` or things like `?`. – user7393973 Mar 16 '17 at 10:03
  • 1
    Well, that was me, but indeed this question is a duplicate, that's why I removed my answer. You should be aware, though, that `\b` word boundary in JS works correctly only with latin letters (i.e., it marks the place in-between a letter and non-letter, string beginning and string end). So for `árvore` it won't work, for example. – raina77ow Mar 16 '17 at 10:05

0 Answers0