I'm attempting to break apart a string using the delimiter \$
, but my attempts so far have been unsuccessful.
You can find the code I've been working with at . I've also included it below for reference.
Question: Can you spot what’s going wrong in this instance when splitting by \$
?
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 doesn't splitting by \$ result in 3 elements as expected, but instead gives 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>