I want to replace all the occurrences of [h2][/h2]
in a JavaScript string
For example, I have
var mystring = 'hii[h2][/h2]';
I want to get -> hii
so far I tried
mystring.replace(/[h2][\/h2]/g, "");
To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')
To replace all occurrences of a string in TypeScript, use the replace() method, passing it a regular expression with the g (global search) flag. For example, str. replace(/old/g, 'new') returns a new string where all occurrences of old are replaced with new .
The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.
Delete all occurrences of a character in javascript string using replaceAll() The replaceAll() method in javascript replaces all the occurrences of a particular character or string in the calling string. The first argument: is the character or the string to be searched within the calling string and replaced.
If you google how to replace all string occurrences in JavaScript, most likely the first approach you’ll find is the use of an intermediate array. Here’s how it works: Split the string into pieces by the search string. Then join the pieces with the replace string in between. For example, let’s replace + with * in the string '1+2+3':
In SQL Server, you can use the T-SQL REPLACE () function to replace all instances of a given string with another string. For example, you can replace all occurrences of a certain word with another word.
The Java String class replaceAll () method returns a string replacing all the sequence of characters matching regex and replacement string. PatternSyntaxException: if the syntax of the regular expression is not valid. Let's see an example to replace all the occurrences of a single character.
Here’s the official syntax: Where string_expression is the string that contains one or more instances of the string (or substring) to replace, string_pattern is the string to replace, and string_replacement is the string to replace it. Here’s an example to demonstrate:
You need to escape the square braces.
var mystring = 'hii[h2][/h2]';
let string = mystring.replace(/\[h2\]\[\/h2\]/g, '');
console.log(string);
Assuming nothing between those tags, you need to escape the []
also.
mystring.replace(/\[h2]\[\/h2]/g, "");
try this one:
str.replace(/\[h2\]\[\/h2\]/g,"");
note that you have to escape [ and ] if they form part of the text you want to replace otherwise they are interpreted as "character class" markers.
If the [h2] and [/h2] could also appear separate, you could use this one:
str.replace(/\[\/?h2\]/g,"");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With