Reputation: 4172
I have string that look like
Temperature is 125
or Temperature is 4
The strings are always the same format, that is, the number always occurrs at the end of the string.
I need to get split these strings where the numbers occur so I will be left with two strings, for example
string1 = Temperature is
string2 = 125
Any ideas how I would do this?
Upvotes: 0
Views: 553
Reputation: 25013
If the item at the end is simply the item after the last space in the string, you can use .lastIndexOf, like
var s='Some text part 1234';
var splitAt = s.lastIndexOf(' ');
document.write('Text = "' + s.substring(0, splitAt) + '"<br />Number = "' + s.substring(splitAt+1) + '"');
Upvotes: 1
Reputation: 6190
Here is a very simple method for you.
var text = "Temperature is (125)";
var result = text.lastIndexOf(" ");
var number = text.substring(result,text.length);
var textBody = text.substring(0,result);
Just check whether you can use this. You have to assume that always the number (with or without brackets) comes as the last word.
Cheers!
Upvotes: 1
Reputation: 23770
Using a regex:
var matches = "Temperature is 125".match(/^(.*) (\d+)$/);
console.log(matches[1]); // Temperature is
console.log(matches[2]); // 125
Upvotes: 5
Reputation: 4901
If you know that the String is always Temperature is XX
, you could do
var str1 = theString.substr(0, 14);
var str2 = theString.substr(15);
EDIT: Whoops, this is a javacript question, not Java
Upvotes: 0