How can we separate the special characters in JavaScript?

In JavaScript, you can separate special characters from text using the match() method with regular expressions. This technique splits strings into arrays containing both word characters and special characters as separate elements.

Syntax

arrayName.flatMap(item => item.match(/\w+|\W+/g));

The regular expression /\w+|\W+/g works as follows:

  • \w+ matches one or more word characters (letters, digits, underscore)
  • | acts as OR operator
  • \W+ matches one or more non-word characters (special characters, spaces)
  • g flag ensures global matching throughout the string

Example: Separating Special Characters from Names

Let's separate special characters from an array of names containing hyphens and percentage symbols:

var allNames = ['John-Smith', 'David', 'Carol%Taylor'];
var output = allNames.flatMap(obj => obj.match(/\w+|\W+/g));
console.log(output);
[
  'John', '-',
  'Smith', 'David',
  'Carol', '%',
  'Taylor'
]

How It Works

The process works in these steps:

  1. flatMap() iterates through each string in the array
  2. match(/\w+|\W+/g) splits each string into word and non-word segments
  3. flatMap() flattens the resulting arrays into a single array

Example: Different Special Characters

var strings = ['hello@world', 'test#123', 'code&run'];
var separated = strings.flatMap(str => str.match(/\w+|\W+/g));
console.log(separated);
[
  'hello', '@',
  'world', 'test',
  '#', '123',
  'code', '&',
  'run'
]

Alternative: Using split() with Regular Expression

You can also use split() to separate words only (removing special characters):

var text = 'John-Smith%Carol@Taylor';
var wordsOnly = text.split(/\W+/);
console.log(wordsOnly);
[ 'John', 'Smith', 'Carol', 'Taylor' ]

Conclusion

Use match(/\w+|\W+/g) with flatMap() to separate both words and special characters into distinct array elements. For extracting only words, use split(/\W+/) instead.

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

367 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements