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
Selected Reading
How to split string when the value changes in JavaScript?
To split a string when the character value changes in JavaScript, you can use the match() method with a regular expression that captures consecutive identical characters.
Syntax
string.match(/(.)\1*/g)
How the Regular Expression Works
The pattern /(.)\1*/g breaks down as:
-
(.)- Captures any single character -
\1- Matches the same character as captured in group 1 -
*- Matches zero or more of the preceding element -
g- Global flag to find all matches
Example
var originalString = "JJJJOHHHHNNNSSSMMMIIITTTTHHH";
var regularExpression = /(.)\1*/g;
console.log("The original string = " + originalString);
var splitting = originalString.match(regularExpression);
console.log("After splitting the original string:");
console.log(splitting);
The original string = JJJJOHHHHNNNSSSMMMIIITTTTHHH After splitting the original string: [ 'JJJJ', 'O', 'HHHH', 'NNN', 'SSS', 'MMM', 'III', 'TTTT', 'HHH' ]
Additional Examples
// Example with numbers
var numberString = "11122233344455";
var numberGroups = numberString.match(/(.)\1*/g);
console.log("Number groups:", numberGroups);
// Example with mixed characters
var mixedString = "aabbccddeeff";
var mixedGroups = mixedString.match(/(.)\1*/g);
console.log("Mixed groups:", mixedGroups);
Number groups: [ '111', '222', '333', '444', '55' ] Mixed groups: [ 'aa', 'bb', 'cc', 'dd', 'ee', 'ff' ]
Alternative Approach Using Loop
function splitOnChange(str) {
if (!str) return [];
var result = [];
var currentGroup = str[0];
for (var i = 1; i < str.length; i++) {
if (str[i] === str[i - 1]) {
currentGroup += str[i];
} else {
result.push(currentGroup);
currentGroup = str[i];
}
}
result.push(currentGroup);
return result;
}
var testString = "AAABBBCCDDD";
console.log("Using loop method:", splitOnChange(testString));
Using loop method: [ 'AAA', 'BBB', 'CC', 'DDD' ]
Conclusion
The match() method with regex /(.)\1*/g provides the most concise way to split strings when character values change. The loop approach offers more control for complex splitting logic.
Advertisements
