0

What is the best way to split a String in jQuery from the first found number.

Example: Speelhof(STE) 0 /W301

I want to split the string in 2 parts (the split must happen on the first found number)

Result should be 2 parts: Speelhof(STE) and 0 /W301

The strings can differ with different numbers, so I would need a way to substring from any number...

Can anyone help me out? Thanks!

0

3 Answers 3

3

You don't want .split because it consumes the delimiter. You can use .match with a regular expression:

"Speelhof(STE) 0 /W301".match(/^(\D+)(.*)$/);

This will give an array with three elements: the string itself, the part that matches \D+ (one or more non-digits) and .* (the rest). So you can use it as:

var arr = "Speelhof(STE) 0 /W301".match(/^(\D+)(.*)$/);
var first = arr[1];   // "Speelhof(STE) "
var second = arr[2];  // "0 /W301"
Sign up to request clarification or add additional context in comments.

Comments

1

This problem is a perfect candidate for regular expressions:

var match = "Speelhof(STE) 0 /W301".match(/^(.+)(\d.+)$/);

You can then access the two components as elements of the returned array: match[1] and match[2].

There's no need to use jQuery here.

To explain how the pattern works: ^ denotes the beginning of the string; (.+) denotes one or more (+) of any character (.), and the parentheses capture this group and allow you to access it in the array that is returned. The second group comprises a digit, \d, followed by one or more of any character, .+, like in the first group. $ denotes the end of the string.

1 Comment

Perfect also! Thanks for the effort!
1

Assuming you have number in the string as you mentioned. You can go through the string and find the first number as a point of division of string.

Live Demo

str = "Speelhof(STE) 0 /W301";

for(i=0; i < str.length; i++)
{    
    if(parseInt(str[i]) >= 0  && parseInt(str[i]) <= 9)
          break;                        
}       

firstPart = str.substring(0, i);
secondPart = str.substring(i+1, str.length);

1 Comment

This also works, although i prefer the other solutions! Way less code! Thanks!

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.