var str; // declaration of the string var final_str = str.replace( / (first_part) .* (second_part)/ , (first_part) + (second_part ));
Note − Here we are trying to find the first occurrence of the ‘first_part’ in the given string, then we will find the last occurrence of the ‘second_part’ in the given string. Then if both the ‘first_part’ and the ‘second_part’ are present in the string and there are some characters present in between them, we will remove them.
We have seen the syntax above to remove part of a string between two characters, now we are going to see the complete algorithm step by step −
First, we will declare the string and assign it some value.
Then we will create a variable that will store the value of the final result.
We will find the regular expression which will include our both starting and ending strings or characters which means they are also going to replace with the middle string which we actually need to return.
We will pass our first and last strings or character as the combined strings to replace the given regular expression.
In this way, we can remove the string between the two parts of the string.
Now, let’s see the examples which are based on the above algorithm −
In this example we will take two strings and will delete the middle string which will be present in between them −
<!DOCTYPE html> <html> <body> <script> var str = "ABCDEFGHIJABCDEFGHIJABCDEFGHIJ"; // declaration of the string var final_str = str.replace( /CD.*GH/ , 'CDGH'); document.write("Previous string was: " + str); document.write("<br>Final stirng is: " + final_str); </script> </body> </html>
In the above example, we have removed all the characters present between the ‘CD’ and ‘GH’. Here we replaced string from index 2 (0-base index) to index 27 and then replace them with ‘CDGH’ to get the final answer.
In this example, we are going to replace all the characters in between two characters and we will remove these characters also.
<!DOCTYPE html> <html> <body> <script> var str = "AB(CDEFGHIJABCDEFGHIJABCDEFGH)IJ"; // declaration of the string var final_str = str.replace(/ *\([^)]*\) */g, ""); document.write("Previous string was: " + str); document.write("<br>Final reuslt is: " + final_str) </script> </body> </html>
In the above example, we have removed all the characters present between the parenthesis including the parenthesis.
- Related Articles
- Replace parts of a string with C# Regex
- Program to check two parts of a string are palindrome or not in Python