I am trying to split the string "1 + 2 / 3 * 4 - 5 " to display "+" "/" "*" "-" to be saved into an array to, the same to be done to the number, so that I call each number and op' into a function to calculate it in BODMAS(/*+-) order.
The string can be longer and shorter as it is a user input calculation.
<p id="demo"></p>
<script>
function myFunction() {
var str = "1+2/3*4-5";
var res = str.split([0-9]);
document.getElementById("demo").innerHTML = res;
}
</script>
2 Answers 2
You do a:
str.split(/\d+/)
to get the symbols and
str.split(/\D+/)
to get the numbers
Comments
You never called the myFunction function. Use a non-maching character at the front, [^0-9]. It will match anything that is not a number. Don't use split. split doesn't recognize [0-9] as a splitting character. Use the string.prototype.match() method instead. It will return an array containing every match.
function myFunction() {
var str = "1+2/3*4-5";
var match=str.match(/[^0-9]+/g);
for(i=0;i<match.length;i++){
document.getElementById('demo').innerHTML+=match[i]+'</br>';
}
}
myFunction();
<p id="demo"></p>
/^, named variables like in the expression2x + 3 = 0, or non-integers like2.3?