JSLearner
JSLearner

Reputation: 79

Remove everything between specific characters in Javascript

In Javascript from the following string

filterExpress = %1 and %2 and %3 and % and %5 and %6 I need to remove anything following "% " (i.e % and a space) and before the immediately next occurrence of %.

So the output string should be-

%1 and %2 and %3 and %5 and %6 I've tried to use regexp as follows

filterExpress = filterExpress.replace(/ % .*[^%]/, ''); However, this doesn't match the results that I want.

Please help me giving a solution.

Upvotes: 2

Views: 128

Answers (4)

Rajesh Paul
Rajesh Paul

Reputation: 7019

Try any the following-

code(using regexp) DEMO

var str = '%1 and %2 and %3 and % and %5 and %6';
str=str.replace(/% [^%]+%/g, '%'); // "%1 and %2 and %3 and %5 and %6"
alert(str);

code(not using regexp) DEMO

var filterExpress = "%1 and %2 and %3 and % and %5 and %6";

//start of logic
while(filterExpress.indexOf("% ")!=-1)
{
    filterExpress=filterExpress.substr(0, filterExpress.indexOf("% "))+filterExpress.substr(filterExpress.indexOf("%",filterExpress.indexOf("% ")+1));
}
//end of logic

alert(filterExpress);

Upvotes: 0

karaxuna
karaxuna

Reputation: 26930

Try this:

var str = '%1 and %2 and %3 and % and %6';
var newStr = '';
for(var i = 0; i < str.length; i++){
    var c = str[i];
    if(c === '%' && str[i+1] === ' '){
        i += ' and '.length;
        continue;
    }
    newStr += c;
}

Upvotes: 0

qw3n
qw3n

Reputation: 6334

Regex that doesn't match the last %

var str='%1 and %2 and %3 and % and %5 and %6';
str=str.replace(/% .+?(?=%)/g,'');
//Match a % followed by a space than then any character until the next %
//but not including it.  Also, do a global replace.

Upvotes: 0

Tibos
Tibos

Reputation: 27823

Here is a short solution:

var str = '%1 and %2 and %3 and % and %5 and %6';
str.replace(/% .*?%/g, '%'); // "%1 and %2 and %3 and %5 and %6"

Regexp explained: matches anything starting with %[space] until the first %. It has the global modifier so it doesn't stop after the first match. It matched both %, so one of them is in the replacement string.

Upvotes: 1

Related Questions