Khoi Hoang
Khoi Hoang

Reputation: 13

Split a String by a Regex in JavaScript

I have the string:

"Vl.55.16b25.3d.42b50.59b30.90.24b35.3d.56.67b70.Tv.54b30.Vl.41b35.Tv.Bd.71b50.3d.99b20.03b50.Tv.73b50.Vl.05b25.12b40.Bd.Tv.82b25."

How to detached get results like:

["Vl.55.16b25", 3d.42.b50.59b30.90.24b35, 3d.56.67b70, ...]

The logic:

Condition 1: The End will be start b and 2 number. Example: b20, b25. If pass condition 1 I need to check condition 2.

Condition 2: maybe like "3d" or 2 characters. If don't match condition 2 we need to pass the next character to the current block.

Many thanks.

Upvotes: 0

Views: 71

Answers (2)

tybocopperkettle
tybocopperkettle

Reputation: 234

If I understand your question correctly, the following code should work:

var string = "Vl.55.16b25.3d.42b50.59b30.90.24b35.3d.56.67b70.Tv.54b30.Vl.41b35.Tv.Bd.71b50.3d.99b20.03b50.Tv.73b50.Vl.05b25.12b40.Bd.Tv.82b25.";
console.log(string.split(/(?<=b\d\d)\.(?=3d)/g))

Explanation:

  • (?<=) is look-behind.
  • b matches the literal character "b".
  • \d matches any digit so \d\d will match two digits in a row.
  • \. matches a literal ".", it needs the \ before it because otherwise it would match any character.
  • (?=) is look-ahead.
  • The g flag stands for global so the string will be split up at every occurrence of the regular expression.

This means that the string will be split at every occurrence of "." that is preceded the letter "b" then two digits, and followed by "3d".

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386868

Assuming you want to separate by last having 'b' and two digits followed by 3d, two digits or the end of string (this is necessary) and by omitting leading dot, you could take the following regular expression.

const
    string = "Vl.55.16b25.3d.42b50.59b30.90.24b35.3d.56.67b70.Tv.54b30.Vl.41b35.Tv.Bd.71b50.3d.99b20.03b50.Tv.73b50.Vl.05b25.12b40.Bd.Tv.82b25.",
    result = string.match(/[^.].*?b\d\d(?=\.(3d|\D\D|$))/g);

console.log(result);

Upvotes: 0

Related Questions