str.IndexOf завершается ошибкой в ​​комбинации строк, разделенных пробелом - PullRequest
0 голосов
/ 31 января 2020

У меня есть функция Javascript, которая выглядит следующим образом. Я вижу, что слова в документе разделены пробелом. Есть идеи, почему это не удается?

var txt = $("tr.trofinterest:first").text().toUpperCase(); //even triedgetting rid of whitespace characters
//.replace("  ", " ").replace("\r", " ").replace("\n", " ")

//and various combination of regex but the function below fails
if (txt.indexOf("TWO WORDS") >= 0) {
  // do sth here //but this is returned false
  console.log("Found TWO WORDS together");
}
//But the folloing statement returns true in all cases
if (txt.indexOf("TWO") >= 0 && txt.indexOf("WORDS") >= 0) {
  console.log("words exist in sentence and i can see they are side by side seperated by space")
}
console.log(txt); //this prints "This tr has text with Two Words which are interesting and the words are side by side"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <!-- nested child tables with a -->
  <tr class='trofinterest'>
    <td>This tr has text with Two Words which are interesting and the words are side by side</td>
  </tr>
</table>

1 Ответ

0 голосов
/ 31 января 2020

Таким образом, в основном, пробельные символы перебираются со строкой, и Firefox не будет отображать строку точно

Мне пришлось сначала преобразовать «пробелы» в «+», используя

txt = txt.toUpperCase().replace(/\s/g, '+'); 
// this gives better visual represntation of the problem
do {
 txt = txt.replace("++", '+'); filter out mutiples to single
   }
while (txt.indexOf("++") >= 0);
if(txt.indexOf("TWO+WORDS")>=0){
console.log("Hey! Hey! Ho! Ho! Not cloning your grandpa has got to go!!!")
}

Изменить для голосования вниз. Меня интересует только "TWO+WORDS" не вся строка. Фактически лучше, если TWO + WORDS находится в оригинальной строке. Иногда нет необходимости перерабатывать решение. Во всяком случае, мой ответ предоставляет метод, чтобы выяснить проблему. Первые шаги в поиске решения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...