Possible to split a string with separator after every word in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

To split a string with separator after every word, the syntax is as follows −

var anyVariableName=yourVariableName.split('parameter').filter(value=>value)

Let’s say, the following is our string with separator −

var sentence="-My-Name-is-John-Smith-I-live-in-US";

Now, split the string with separator as in the below code.

Example

var sentence="-My-Name-is-John-Smith-I-live-in-US";
console.log("The value="+sentence);
var result=sentence.split('-').filter(value=>value)
console.log("After split()=");
console.log(result);

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

node fileName.js.

Here, my file name is demo63.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo63.js
The value=-My-Name-is-John-Smith-I-live-in-US
After split()=
[
   'My', 'Name',
   'is', 'John',
   'Smith', 'I',
   'live', 'in',
   'US'
]
raja
Published on 03-Sep-2020 07:26:37
Advertisements