I have a problem in the american-british translator. For the moment, i have implemented the routes of the application and I want to implement the translator itself.
Let’s focus on the translation of words. First, I implemented something that worked, but I encountered some issues. For example, “paracetamol” from british to american was translated “paraceThank youmol”, because “ta” has a translation from british to american.
So I tried to make a regex which match the word if it is at the beginning or the end of the tring or if it is surrounded by spaces.
This is the regex : /(?<=\s|^)(word)(?=\s|$)/gi
I tested it on https://regex101.com/ and it has the expected behaviour.
So here is the code I made to translate a sentence and let’s test it for the string “I try to acclimate myself to this cold weather”
translate(text, mode){
let newString = text;
if(mode === "american-to-british"){
//transationList is an array of arrays. Each array contains the word in american and the corresponding word in british
translationList.forEach(translation => {
if(translation[0]==="acclimate"){
//I put this so only one console log is shown
let regWord = new RegExp("(?<=\s|^)("+translation[0]+")(?=\s|$)", "gi");
console.log(translation[0]); //shows "acclimate" as expected
console.log(translation[1]); //shows "acclimatise" as expected
console.log(regWord); //shows the regex as expected
console.log(newString.match(regWord)); //shows null
newString = newString.replace(regWord, translation[1]);
}
});
}
}
Hmm I see two problems :
If i put “paracetamol” at the beginning of the string, it becomes “paracethank youmol” again but if i put it at the middle or at the end, it works properly.
Also, it translates the word if it is inside another word, so if I write “paracetamoleee”, it is translated as “Typhenoleee”.
So that’s why i wanted to try using a regex to be sure the word was actually a word and not a part of another word.