How can we separate the special characters in JavaScript?

To separate the special character, use the concept of match() with Regular Expression. The syntax is as follows −

yourStringName.flatMap(anyVariableName => yourVariableName.match(/\w+|\W+/g));

Let’s say, the following is our array with special characters in between values −

var allNames = ['John-Smith', 'David', 'Carol%Taylor'];

Let’s now see how to separate text with special characters. Following is the code −


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

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo32.js.


This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo32.js
   'John', '-',
   'Smith', 'David',
   'Carol', '%',