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
How to get substring between two similar characters in JavaScript?
In JavaScript, extracting a substring between two similar characters is a common task when parsing strings. This article explores different methods to achieve this using built-in string methods.
Understanding String Methods
Before diving into the solution, let's understand the key methods we'll use:
The substring() method extracts characters between two indices and returns a new string without modifying the original.
Syntax
string.substring(start, end)
The split() method divides a string into an array of substrings based on a specified separator.
Syntax
string.split(separator, limit)
Method 1: Using split()
The simplest approach is to split the string by the delimiter character and access the desired array element:
<!DOCTYPE html>
<html>
<body>
<script>
const str = 'one:two:three';
const result = str.split(':');
document.write('Substring between colons: ' + result[1]);
</script>
</body>
</html>
Substring between colons: two
Method 2: Using Regular Expressions with split()
For multiple delimiters, use regular expressions to split on any of the specified characters:
<!DOCTYPE html>
<html>
<body>
<script>
const str = 'Hello:World;Welcome:JavaScript;';
const parts = str.split(/[:;]/);
document.write('Second part: ' + parts[1] + '<br>');
document.write('Fourth part: ' + parts[3]);
</script>
</body>
</html>
Second part: World Fourth part: JavaScript
Method 3: Using indexOf() and substring()
For more control, find the positions of delimiters and extract the substring manually:
<!DOCTYPE html>
<html>
<body>
<script>
const str = 'start*middle*end';
const firstIndex = str.indexOf('*');
const secondIndex = str.indexOf('*', firstIndex + 1);
if (firstIndex !== -1 && secondIndex !== -1) {
const result = str.substring(firstIndex + 1, secondIndex);
document.write('Substring between asterisks: ' + result);
}
</script>
</body>
</html>
Substring between asterisks: middle
Method 4: Using slice() with Character Positions
When you know the exact positions, slice() provides a direct approach:
<!DOCTYPE html>
<html>
<body>
<script>
const str = 'abc|The Best Learning Platform|xyz';
const result = str.slice(4, 32);
document.write('Extracted text: ' + result);
</script>
</body>
</html>
Extracted text: The Best Learning Platform
Comparison of Methods
| Method | Best For | Flexibility |
|---|---|---|
split() |
Single delimiter | High |
split() with regex |
Multiple delimiters | Very High |
indexOf() + substring() |
Complex parsing | Very High |
slice() |
Known positions | Low |
Conclusion
Use split() for simple cases with known delimiters, and combine indexOf() with substring() for more complex string parsing scenarios. Choose the method that best fits your specific use case.
