Splitting a hyphen delimited string with negative numbers or range of numbers - JavaScript?


Let’s say we have the following hyphen delimited string with negative or range of numbers −

var firstValue = "John-Smith-90-100-US";
var secondValue = "David-Miller--120-AUS";

To split, use regular expressions. Following is the code −

Example

Following is the code −

var firstValue = "John-Smith-90-100-US";
var secondValue = "David-Miller--120-AUS";
var regularExpression = /-(?=[A-Za-z-]|\d+-\d)/;
var result1 = firstValue.split(regularExpression);
var result2 = secondValue.split(regularExpression);
console.log(result1);
console.log(result2);

To run the above program, use the following command −

node fileName.js.

Here, my file name is demo241.js.

Output

The output is as follows −

PS C:\Users\Amit\javascript-code> node demo241.js
[ 'John', 'Smith', '90-100', 'US' ]
[ 'David', 'Miller', '-120', 'AUS' ]

Updated on: 03-Oct-2020

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements