2

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.

2
  • Welcome to Stack Overflow. Please be more specific in what should result when running this code, and also providing attempts to solve the issue. Commented Dec 4, 2013 at 13:48
  • Sorry new to the forum and just started using javascript filterExpress = "%1 and %2 and %3 and % and %5 and %6" and output should be "%1 and %2 and %3 and %5 and %6". I have tried filterExpress = filterExpress.replace(/ % .*[^%]/, '') Commented Dec 4, 2013 at 13:50

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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;
}

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.