0

Hi I'm going to make a calculator and I want a +/- button. I want to get the latest *, -, +, / in the string and define whats the laststring.

For example:

str="2+3*13"

I want this to be split into:

strA="2+3*"

strB="13"

Another example:

str="3-2+8"

Should split into:

strA="3-2+"

strB="8"
0

3 Answers 3

3

Use lastIndexOf and one of the substring methods:

var strA, strB,
    // a generic solution for more operators might be useful
    index = Math.max(str.lastIndexOf("+"), str.lastIndexOf("-"), str.lastIndexOf("*"), str.lastIndexOf("/"));
if (index < 0) {
    strA = "";
    strB = str;
} else {
    strA = str.substr(0, index+1);
    strB = str.substr(index+1);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hmmm... This one's GREAT, I'll try it
0

You can use replace, match, and Regular Expressions:

str="3-2+8"
strA = str.replace(/\d+$/, "")
strB = str.match(/\d+$/)[0]

console.log(str, strA, strB);
> 3-2+8 3-2+ 8

2 Comments

@user210000: replace does not modify the str, so why not?
As @Bergi said: the original str variable is not modified in any way during this entire operation (as evident by the console.log at the end of the code block). The .replace() function is used specifically for the purpose of setting strA to the desired value.
0

You can use regular expression and split method:

var parts = "2 + 4 + 12".split(/\b(?=\d+\s*$)/);

Will give you and array:

["2 + 4 + ", "12"]

Couple of tests:

"(2+4)*230" -> ["(2+4)*", "230"]
"(1232-74) / 123 " -> ["(1232-74) / ", "123 "]
"12 * 32" -> ["12 * ", "32"]

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.