tags:

views:

673

answers:

4

Hi,

What would be the cleanest way of doing this that would work in both IE and firefox.

My string looks like this: sometext-20202

Now the 'sometext' and the integer after the dash can be of varying length.

Should I just use substring and index of or is the other ways?

+2  A: 
var the_string = "sometext-20202";
var parts = the_string.split('-', 2);

// After calling split(), 'parts' is an array with two elements:
// parts[0] is 'sometext'
// parts[1] is '20202'

var the_text = parts[0];
var the_num  = parts[1];
Sean Bright
A: 

Use a regular expression of the form: \w-\d+ where a \w represents a word and \d represents a digit. They won't work out of the box, so play around. Try this.

dirkgently
A: 

AFAIK, both substring() and indexOf() are supported by both Mozilla and IE. However, note that substr() might not be supported on earlier versions of some browsers (esp. Netscape/Opera).

Your post indicates that you already know how to do it using substring() and indexOf(), so I'm not posting a code sample.

Cerebrus
+2  A: 

How I would do this:

// function you can use:
function getSecondPart(str) {
    return str.split('-')[1];
}
// use the function:
alert(getSecondPart("sometext-20202"));
artlung