Jim_CS
Jim_CS

Reputation: 4172

Splitting string into numbers and text

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

Answers (4)

Andrew Morton
Andrew Morton

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 = &quot;' + s.substring(0, splitAt) + '&quot;<br />Number = &quot;' + s.substring(splitAt+1) + '&quot;');

Upvotes: 1

Prasad Rajapaksha
Prasad Rajapaksha

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

clyfe
clyfe

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

josh.trow
josh.trow

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

Related Questions