Separate a string with a special character sequence into a pair of substrings in JavaScript?

When you have a string containing a special character sequence that acts as a delimiter, you can separate it into substrings using JavaScript's split() method with regular expressions.

Problem Statement

Consider this string with a special character sequence:

" John  Smith "

We need to split this string at the <----> delimiter and get clean substrings without extra whitespace.

Syntax

var regex = /\s*\s*/g;
var result = string.trim().split(regex);

Example

var fullName = " John  Smith ";
console.log("Original string: " + fullName);

var regularExpression = /\s*\s*/g;
var separatedNames = fullName.trim().split(regularExpression);

console.log("Separated names:");
console.log(separatedNames);
console.log("First name: " + separatedNames[0]);
console.log("Last name: " + separatedNames[1]);
Original string:  John  Smith 
Separated names:
[ 'John', 'Smith' ]
First name: John
Last name: Smith

How It Works

The regular expression /\s*<---->\s*/g breaks down as follows:

  • \s* - Matches zero or more whitespace characters before the delimiter
  • <----> - Matches the literal character sequence (angle brackets need escaping)
  • \s* - Matches zero or more whitespace characters after the delimiter
  • g - Global flag to match all occurrences

Multiple Delimiters Example

var multipleNames = " Alice  Bob  Charlie ";
var regex = /\s*\s*/g;
var names = multipleNames.trim().split(regex);

console.log("Multiple names:");
console.log(names);
Multiple names:
[ 'Alice', 'Bob', 'Charlie' ]

Conclusion

Use split() with regular expressions to separate strings at custom delimiters. The regex pattern handles whitespace around delimiters, producing clean substrings ready for use.

Updated on: 2026-03-15T23:18:59+05:30

733 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements