views:

306

answers:

4

Is there a way to get a piece of code that is not between quotes (single or double) in javascript with regular expressions?

if i have this string:

'this is a test "this shouldn't be taken"'

the result should be:

'this is a test'
A: 
myString.replace(/".*?"/g, '')

will remove any string between double-quotes from myString. It doesn't handle escaped double-quotes, though.

Alsciende
A: 

You could remove the quoted part of your string with the javascript replace function:

str = 'this is a test "this shouldn\'t be taken"';
str_without_quotes = str.replace(/(['"]).*?\1/g, "") // => 'this is a test '
Daniel Vandersluis
This is a good answer, but it doesn't work if there is a line break in the string.
Prestaul
+2  A: 

This should remove anything between single or double quotes, it works with multi-line strings (strings that contain \n or \r) and it should also handle escaped quotes:

var removeQuotes = /(['"])(?:\\?[\s\S])*?\1/g;

var test = 'this is a test "this shouldn\'t be taken"';
test.replace(removeQuotes, ""); // 'this is a test '

test = 'this is a test "this sho\\"uldn\'t be taken"';
test.replace(removeQuotes, ""); // 'this is a test '
Prestaul
A: 

thanks Prestaul your solution works well

mck89
Accept it, then: http://stackoverflow.com/questions/279995/accepting-answers-what-is-it-all-about/279997#279997
Miles