ప్రధాన కంటెంట్‌కు వెళ్లండి
eLearner.app
మాడ్యూల్ 7 · 4లో పాఠం 4కోర్సులో 28/32~10 min
మాడ్యూల్ పాఠాలు (4/4)

రెజెక్స్‌తో విభజించండి

String.prototype.split(separator) accepts not only a fixed string but also a regex as separator. This makes it a powerful tool to tokenize structured text.

JS
'uno, due,tre  quattro'.split(/[,\s]+/);
// ["uno", "due", "tre", "quattro"]

The regex /[,\s]+/ matches "one or more of comma or whitespace": split splits on any compound delimiter.

Typical cases

  • Permissive CSV: text.split(/\s*,\s*/) to handle spaces around commas.
  • Naive tokenizer: text.split(/\s+/) to extract words.
  • Keep the separator: if the regex contains capturing groups, the content of the groups is included in the result array.
JS
'a=1; b=2; c=3'.split(/(;)\s*/);
// ["a=1", ";", "b=2", ";", "c=3"]

Without the () group the semicolon would disappear. With (;) you keep it in the result.

Preserving separators in split operations

If you place split separators inside capturing parentheses, the output of String.prototype.split will include the separators themselves as elements in the final array, instead of discarding them.

Try it

వ్యాయామం#regex.m7.l4.e1
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Find every permissive CSV separator: a comma with optional spaces around it. This way you could use it in split to tokenize the list.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

Use \\s* before and after the comma to absorb any optional spaces.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది

Review exercise

వ్యాయామం#regex.m7.l4.e2
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Find every 'spaces or semicolons' separator (one or more). This way split would tokenize the text into words.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

Combine \\s and ; in a class [\\s;] with the + quantifier.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది

Additional challenge

వ్యాయామం#regex.m7.l4.e3
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Write a regex to use in a split that separates numbers while keeping math operators `+`, `-`, `*`, `/` as elements of the array.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

Enclose the math operators character class in capture parentheses to preserve them in the split array.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది