1
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(var i = 0;i<cnt;i++){
  str = str.replace(/.{1}\[BACK\]{1}/i,""); //remove backspace and one character before it.
}

The above script returns something like "[BACK it's a test string" I need to get this result as "it's a test string" please help me....

  • Am i right when saying you want to emulate a backspace keystroke with regex? So for every single [BACK] instance a leading character is removed? – ChrisR Dec 22 '11 at 07:37

4 Answers4

2

It's easier to do this without a regex actually.

String.prototype.replaceFromIndex=function(index, length, replace) {
    return this.substr(0, index) + replace + this.substr(index+length);
}

var search = '[BACK]';
var str="itss[BACK][BACK][BACK][BACK][BACK][BACK] it's a test stringgg[BACK][BACK]";

while((index = str.indexOf(search)) >= 0){
    str = str.replaceFromIndex(index-1, search.length+1, '');    
}

alert(str);

Check http://jsfiddle.net/fRThH/2/ for a working example. Wrap it in a function and you are ready to go!

Courtesy to Cem Kalyoncu ( https://stackoverflow.com/a/1431113/187018 ) for a slightly modified version of String.prototype.replaceAt

Community
  • 1
  • 1
ChrisR
  • 14,370
  • 16
  • 70
  • 107
1

My idea is to count all the backspaces [BACK] and then replace them with an empty string one by one:

var str="itss[BACK][BACK][BACK][BACK][BACK][BACK] it's a test stringgg[BACK][BACK]";

var backspaces = str.match(/\[BACK\]/g).length;

for(i=0; i<backspaces; i++)
{
    str = str.replace(/.?\[BACK\]/, '');
}
document.write( str );

working example: jsFiddle

Teneff
  • 30,564
  • 13
  • 72
  • 103
0

If I understood correctly

var dat = str.split('[BACK]').filter(function(e){return e})[1];

here is the working demo.

Exception
  • 8,111
  • 22
  • 85
  • 136
0

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:

Jesufer Vn
  • 13,200
  • 6
  • 20
  • 26