gpt4 book ai didi

javascript - JavaScript 中的字符串拆分不正确

转载 作者:行者123 更新时间:2023-11-30 07:19:56 26 4
gpt4 key购买 nike

我正在尝试根据定界符 \$ 拆分字符串。我试过这个没有成功。

我的代码在 https://js.do/sun21170/77657 ,也粘贴在下面。

问题:当按\$ 分割时,我在这个例子中做错了什么?

var trickyString = "sd sewq wee r r ttttt $300 rrtrt utu iwiwi \$500 kjgf ihj \$215 ghi"; 

//document.getElementById("div0").innerHTML = trickyString;

function splitString() {
//Why is splitting by \$ not giving 3 elements but is instead giving 4 elements?
var array1 = trickyString.split(/\$/);
document.getElementById("div1").innerHTML = "<b>Length = " + array1.length + "</b>";
for (var i = 0; i < array1.length; i++) {
document.getElementById("div1").innerHTML += "<br>" + array1[i];
}

var array2 = trickyString.split("$");
document.getElementById("div2").innerHTML = "<b>Length = " + array2.length + "</b>";
for (var j = 0; j < array1.length; j++) {
document.getElementById("div2").innerHTML += "<br>" + array2[j];
}
}
<button onclick="splitString();return false;">Split a tricky string</button>

<h4>Tricky string</h4>
<div id="div0" style="color:green">sd sewq wee r r ttttt $300 rrtrt utu iwiwi \$500 kjgf ihj \$215 ghi</div>

<h4>Split using \$ as delimiter</h4>
<div id="div1" style="color:red"></div>

<h4>Split using $ as delimiter</h4>
<div id="div2" style="color:blue"></div>

最佳答案

您的问题源于以下事实:在您的正则表达式 /\$/ 中,\$ 被解释为请求 $被视为文字字符。

您应该使用的正则表达式是 /\\\$/。如上所示 regex101.com

\\ matches the character \ literally (case sensitive)
\$ matches the character $ literally (case sensitive)

enter image description here

您的字符串中也遇到了类似的问题,您在其中放置 \$,它被视为逐字使用字符 $ 的请求。如果您执行 console.log(trickyString); 就可以看到这一点,您会注意到 \ 不在输出中。您需要双重转义引号:

const trickyString = "sd sewq wee r r ttttt $300 rrtrt utu iwiwi \\$500 kjgf ihj \\$215 ghi;"

关于javascript - JavaScript 中的字符串拆分不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52874498/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com