One of the problems that I found out was that you didn't set a condition in which you would not have to remove the first character when the string '[BACK]'
is in position zero.
Well, the solution I am posting here first search for the position of the first '[BACK]'
string, and then creates a substring of the characters that we want to remove, so, if there is a character before the string '[BACK]'
, it is included in the substring. Then, the substring is removed from the main string, and it continues looping until all the '[BACK]'
s are removed.
var str = "itss[BACK][BACK][BACK][BACK][BACK][BACK] it's a test stringgg[BACK][BACK]";
var word = '[BACK]';
var substrings = str.split(word);
var cnt = substrings.length - 1;
for (i = 0; i < cnt; i++) {
pos = str.search("[BACK]");
if (pos - 1 > 0) {
str = str.replace(str.substring(pos - 2, pos + 5), '');
} else {
str = str.replace(str.substring(pos - 1, pos + 5), '');
}
}
Here is the code in jsfiddle: