poitroae
poitroae

Reputation: 21367

Replace string everywhere except if its within quotes

I would like to replace all :) by :D, except if they are within quotes "

Example 1:

Hey man :D, how're you? :) My friend told me "this can't be true :)"

becomes

Hey man :D, how're you? :D My friend told me "this can't be true :)"

As you see, :) is not replaced if it's enclosed by ". If this condition wouldn't be there, it would be quite simple, right? I am using Javascript (jQuery) for all this.

If this is not plainly possible with a regex, what would be an alternate suggestion?

Upvotes: 4

Views: 1417

Answers (3)

abe1432181
abe1432181

Reputation: 1316

If you need variables to control of this - then you could try

function doReplace(find, repl, str, fullWordsOnly, ignoreSQuotes,  ignoreDQuotes, caseSensitive) {
   if (caseSensitive == undefined) caseSensitive = false;

   var flags = 'gm';
   if (!caseSensitive) flags += 'i';

   var control = escapeRegExp(find);
   if (ignoreDQuotes) control = '(?!\\B"[^"]*)' + control + '(?![^"]*"\\B)';
   if (ignoreSQuotes) control = '(?!\\B\'[^\']*)' + control + '(?![^\']*\'\\B)';
   if (fullWordsOnly) control = '\\b' + control + '\\b';

   return str.replace(new RegExp(control, flags), repl);

}

Note, this will probably have problems with single quotes when using abbreviated words such as how're and can't, so I've also included a hack to fix against that:

// Fix any abbreviated words ('re or 't) 
str=str.replace(/'re\/b/gi, ''re');
str=str.replace(/'t\b/gi, ''t');

See http://jsfiddle.net/Abeeee/ct7vayz5/4/ for a working demo

Upvotes: 0

anubhava
anubhava

Reputation: 784898

Assuming no double quote is unbalanced, this is the regex that should work for you:

:\)(?=(?:(?:[^"]*"){2})*[^"]*$)

Explanation: This regex is using a positive lookahead that basically is matching 0 or more occurrences of a pair of some text until a double quote is found i.e. ([^"]*"){2} on the right hand side (RHS) of every match of :).

Which in simple term means replace a :) only if it is outside double quotes since all the matches inside double quotes will have odd number of [^"]*" matches on RHS.

Live Demo: 1. http://www.rubular.com/r/3aixZy5bYR

Live Demo: 2. http://ideone.com/C679NW

Upvotes: 6

Ohgodwhy
Ohgodwhy

Reputation: 50767

function parseSmiley(str){
    return str.replace(/(?!"):\)(?!")/g, ":D");
}

console.log(parseSmiley('Hey man :D, how\'re you? :) My friend told me "this can\'t be true :)"');

And the fiddle with an input so you can test.

Basically, we just replace all instances of :) not encased in " " with :D

Upvotes: 0

Related Questions