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 remove two parts of a string with JavaScript?
This tutorial teaches us how to remove the text part between two parts of a string with JavaScript. We are given two ends that can be a string or a character and we need to remove the string lying in between them.
We will use regular expressions with JavaScript's replace() method to accomplish this task.
Syntax
Here's the basic syntax for removing part of a string between two characters or sub-strings:
var str = "your string here"; var final_str = str.replace(/(first_part).*?(second_part)/, '$1$2');
In the above syntax:
-
first_part- The starting delimiter (string or character) -
.*?- Matches any characters between the delimiters (non-greedy) -
second_part- The ending delimiter -
$1$2- Keeps only the first and second parts, removing everything in between
Method 1: Removing Content Between Two Strings
This example removes all characters between 'CD' and 'GH', keeping the delimiters:
<!DOCTYPE html>
<html>
<body>
<script>
var str = "ABCDEFGHIJABCDEFGHIJABCDEFGHIJ";
var final_str = str.replace(/CD.*?GH/, 'CDGH');
document.write("Previous string was: " + str);
document.write("<br>Final string is: " + final_str);
</script>
</body>
</html>
Previous string was: ABCDEFGHIJABCDEFGHIJABCDEFGHIJ Final string is: ABCDGHIJABCDEFGHIJ
Method 2: Removing Content Between Parentheses
This example removes everything between parentheses, including the parentheses themselves:
<!DOCTYPE html>
<html>
<body>
<script>
var str = "AB(CDEFGHIJABCDEFGHIJABCDEFGH)IJ";
var final_str = str.replace(/ *\([^)]*\) */g, "");
document.write("Previous string was: " + str);
document.write("<br>Final result is: " + final_str);
</script>
</body>
</html>
Previous string was: AB(CDEFGHIJABCDEFGHIJABCDEFGH)IJ Final result is: ABIJ
Method 3: Multiple Occurrences with Global Flag
To remove multiple occurrences, use the global flag g:
<!DOCTYPE html>
<html>
<body>
<script>
var str = "Hello [world] and [universe]!";
var final_str = str.replace(/\[[^\]]*\]/g, "");
document.write("Previous string was: " + str);
document.write("<br>Final result is: " + final_str);
</script>
</body>
</html>
Previous string was: Hello [world] and [universe]! Final result is: Hello and !
Key Points
- Use
.*?for non-greedy matching (stops at first occurrence) - Use
.*for greedy matching (matches until last occurrence) - Add the
gflag to remove all occurrences - Escape special regex characters like
(,),[,]with backslashes
Conclusion
JavaScript's replace() method with regular expressions provides a powerful way to remove text between two delimiters. Use non-greedy matching and the global flag for precise control over what gets removed.
