1

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>
6
  • 6
    What is your question? Commented Feb 9, 2015 at 21:49
  • 1
    You probably want a regular expression, those generally start and end with / Commented Feb 9, 2015 at 21:50
  • jsfiddle.net/9k9v09ds Commented Feb 9, 2015 at 21:51
  • I would look for a calculator parser such as...jorendorff.github.io/calc/docs/calculator-parser.html Commented Feb 9, 2015 at 21:52
  • Do you need something that handles other operators, like ^, named variables like in the expression 2x + 3 = 0, or non-integers like 2.3? Commented Feb 9, 2015 at 22:19

2 Answers 2

2

You do a:

str.split(/\d+/)

to get the symbols and

str.split(/\D+/)

to get the numbers

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.