用反斜杠分割的字符串不会分割

当我用反斜杠分割字符串时,它并不是真正的分割。相反,它似乎正在消除反斜杠

我尝试了不同的组合。但似乎没有一个像我预期的那样工作。

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display the array values after the split.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  var str = "How\are you doing today?";
  var res = str.split("\\");
  console.log('res is',res);
  document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

我希望变量res到具有2个值的数组,第一个是“如何”,第二个是“您今天在做什么?”。但是res是1个值的数组,表示“您今天在做什么?”

jack11666 回答:用反斜杠分割的字符串不会分割

由于反斜杠是未转义的转义字符,因此您不会在原始字符串中找到它,因此split()不会发现任何可拆分的内容,因此返回了原始字符串

var str = "How\are you doing today?"; // backslash is an escape character...
console.log("My string: ",str); // So you won't find it in the string
var res = str.split("\\");
console.log('My String again: ',res[0]); // That's because you get back the original string

本文链接:https://www.f2er.com/3138831.html

大家都在问