Trying to find substring of string that equals "\" in javascript

Viewed 51

What I'm trying to do is compare the order of backslashes in 2 texts (one is English text, the other is user inputted translated text). I first do an if statement to make sure both texts have backslashes and then create separate lists for the two texts in order to compare the order. NOTE: if sourcetext has a backslash, in dev tools, it does show as "\".

But even though I know there's a backslash at a specific index, my code isn't placing that sourcetext.substring(w+1, 1) into my tokenlist... Not sure where to fix my bug and/or why it's not recognizing the comparison of the substring and "\". The output I want from the tokenlist is:

tokenlist = "\\n\\n\\t";

But instead I get nothing put into tokenlist. Any insight would be appreciated!

var sourcetext = "Example \n\t\n";
var newtext = "Exemple \n\t\n";

if (newtext.includes('\\') && sourcetext.includes('\\')) {
  var tokenlist = "";
  var tokenlisttran = "";

  for (let w = 0; w < sourcetext.length - 1; w++) {
    if (sourcetext.substring(w, 1) == "\\") {
      tokenlist += "\\" + sourcetext.substring(w + 1, 1);
    }
  }

  for (let i = 0; i < newtext.length - 1; i++) {
    if (newtext.substring(i, 1) == "\\") {
      tokenlisttran += "\\" + newtext.substring(i + 1, 1);
    }
  }
}

console.log(tokenlist,tokenlisttran)

0 Answers
Related