I have a string will have atleast one whitespace, in that case its easier to use the

string.split(" ") to get 2 elements in an array. Ex:

var string = "ABC123 JAck3939";
string.split(" ") // o/p: ["ABC123", "JAck3939"];

however there might be a case where I may have multiple spaces: Ex:

var string = "ABC 123 JAck 123333"

In above case, I would still want to separate out:

"ABC 123" and "JAck 123333"

but using string.split(" ") will give me:

["ABC", "123", "JAck", "123333"]

instead Im trying to get 2 elements, one with "ABC 123" and "JAck 123333" In this case I'm not worried about the spaces between "ABC 123" and "JAck 123333"

possible scenarios:

string = "ABC122 JACK333",
string = "ABC 122 JACK333",
string = "ABC 122 JACK 333",
string = "ABC122 JACK 333"

Here is the fiddle I have created: https://jsfiddle.net/qdoLvhz3/32/

The reason I was trying to get these whitespaces eliminated was coz I wanted to get following in the o/p

Name: ABC
Id: 32423
Address: Jack
Code: 43453

Now a valid input field value will have

  • letters+numbers (space) letters+numbers
  • letters(space) numbers (space) letters (space) numbers
  • letters+numbers (space) numbers+letters

so when a user types:

string = "something322somethingALL433"

this will be invalid string as there is no space between the first set of letters+numbers (i.e, "something322" and "somethingALL433")

Currently with my code when a user types: string = "abd32xys6472" the o/p I get is:

Name: abdxys
Id: 326472

Instead i try to get:

Name:abd
Id:32
Address:xys
Code:6472

hope this makes sense!

1 Answers

1
Barmar On Best Solutions

Use a regular expression to match a sequence of letters followed by a sequence of numbers, with optional whitespace between them.

function get_strings(str) {
  var m = str.match(/([a-z]+\s*\d+)\s+([a-z]+\s*\d+|\d+\s*[a-z]+)/i);
  return m && m.slice(1);
}
console.log(get_strings("ABC122 JACK333"))
console.log(get_strings("ABC 122 JACK333"))
console.log(get_strings("ABC 122 JACK 333"))
console.log(get_strings("ABC122 JACK 333"))
console.log(get_strings("test444 444test"))

  • [a-z]+ matches a series of letters
  • \d+ matches a series of digits
  • \s* matches zero or more whitespace characters
  • \s+ matches at least 1 whitespace character, which is required between the first and second parts of the string
  • | separates alternatives -- this allows the second capture to be either letters+numbers or numbers+letters
  • () surrounds capture groups, which are returned as additional elements of the array
  • i makes the letter matching case-insensitive
  • m.slice(1) discards the first element of the array, which is the entire match, so we just return what matched the capture groups.