Ice Jungrai
Ice Jungrai

Reputation: 385

How can I obtain substrings from a string in javascript?

I have a string that looks like this:

var stringOriginal = "72157632110713449SomeDynamicText";

I want to separate this string into two substrings:

I want these stored in two separate variables, like this:

var string1 = "72157632110713449"; //First static 17 digits
var string2 = "SomeDynamicText";   // Dynamic Text

Upvotes: 0

Views: 251

Answers (4)

HBP
HBP

Reputation: 16033

Assuming that you want to split the string by separating initial digits from the rest regardless of length :

 string = string.match (/^(\d+)(.*)/) || [string, '', ''];

string[1] will hold the initial digits, string[2] the rest of the string, the original string will be in string[0].

If string does not start with a digit, string[0] will hold the original string and string[1] and string[2] will be empty strings.

By changing the code to :

 string = string.match (/^(\d*)(.*)/);

strings containing no initial digits will have string[1] empty and string[2] will have the same value as string[0], i.e the initial string. In this case there is no need to handle the case of a failing match.

Upvotes: 0

NT3RP
NT3RP

Reputation: 15370

Assuming your string is fixed, you can use the substring or substr string functions. The two are very similar:

  • substr(start, length) obtains a value from the start index to a specified length (or to the end, if unspecified)
  • substring(start, end) obtains a value from the start index to the end index (or the end, if unspecified)

So, one way you could do it by mixing and matching the two, is like this:

var string1 = stringOriginal.substring(0, 17);
# interestingly enough, this does the same in this case
var string1 = stringOriginal.substr(0, 17);

var string2 = stringOriginal.substr(17);

If, however, you need a more sophisticated solution (e.g. not a fixed length of digits), you could try using a regex:

var regex   = /(\d+)(\w+)/;
var match   = regex.exec(stringOriginal);
var string1 = match[1]; // Obtains match from first capture group
var string2 = match[2]; // Obtains match from second capture group

Of course, this adds to the complexity, but is more flexible.

Upvotes: 2

KingKongFrog
KingKongFrog

Reputation: 14419

Here you go:

string1 = stringOriginal.substring(0, 17);
string2 = stringOriginal.substring(17, stringOriginal.length);

or

string2 = stringOriginal.substring(17); 
//Second parameter is optional. The index where to stop the extraction. 
//If second parameter is omitted, it extracts the rest of the string

Upvotes: 1

timc
timc

Reputation: 2174

This will split the string into vars given that the first 17 characters always go into string1 and the remainder into string2.

var string1 = stringOriginal.substring(0,17);
var string2 = stringOriginal.substring(17,stringOriginal.length);

Upvotes: 0

Related Questions