Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Splitting a hyphen delimited string with negative numbers or range of numbers - JavaScript?
When working with hyphen-delimited strings containing negative numbers or ranges, simple split('-') won't work correctly because it treats every hyphen as a delimiter. We need regular expressions to distinguish between separating hyphens and negative number signs.
The Problem
Consider these strings with mixed content:
var firstValue = "John-Smith-90-100-US"; var secondValue = "David-Miller--120-AUS";
Using split('-') would incorrectly split negative numbers and ranges, giving unwanted empty strings and broken values.
Solution Using Regular Expression
We use a lookahead pattern to split only at hyphens that precede letters or number ranges:
var firstValue = "John-Smith-90-100-US";
var secondValue = "David-Miller--120-AUS";
// Regular expression with positive lookahead
var regularExpression = /-(?=[A-Za-z-]|\d+-\d)/;
var result1 = firstValue.split(regularExpression);
var result2 = secondValue.split(regularExpression);
console.log("First string result:", result1);
console.log("Second string result:", result2);
First string result: [ 'John', 'Smith', '90-100', 'US' ] Second string result: [ 'David', 'Miller', '-120', 'AUS' ]
How the Regular Expression Works
The pattern /-(?=[A-Za-z-]|\d+-\d)/ breaks down as:
-
-? matches a hyphen -
(?=...)? positive lookahead (doesn't consume characters) -
[A-Za-z-]? matches if followed by a letter or hyphen -
|\d+-\d? OR matches if followed by a number range pattern
Alternative Approach
For more complex scenarios, you can use a more comprehensive pattern:
var complexString = "Product-Name-123-456--78-Category";
var advancedPattern = /-(?=[A-Za-z])|(?<!\d)-(?=\d+$)|(?<=\d)-(?=[A-Za-z])/;
var result = complexString.split(advancedPattern);
console.log("Complex split result:", result);
Complex split result: [ 'Product', 'Name', '123-456--78', 'Category' ]
Conclusion
Regular expressions with lookahead patterns effectively handle hyphen-delimited strings containing negative numbers and ranges. The key is distinguishing between separating hyphens and those that are part of the data values.
