2009-06-30 3 views
1

JavaScriptが正規表現で引用符(シングルまたはダブル)の間にないコードを取得する方法はありますか?javascriptのregexpで引用符外のコードを取得する

私はこの文字列を持っている場合:

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

結果は次のようになります。

'this is a test' 
+1

あなたの文字列があるため – Alsciende

+1

結果は最後のスペースで「これはテストです」あるべき「べきではない」の引用で、有効ではありませんすべきではないですか? – Alsciende

+0

私は、一重引用符と二重引用符の間にはないと言っていますが、解決策は一重引用符で囲まれています。 –

答えて

1
myString.replace(/".*?"/g, '') 

はのmyStringから二重引用符の間の任意の文字列を削除します。しかし、二重引用符はエスケープされません。

0

あなたはjavascriptのreplace機能を使って、文字列の引用符で囲まれた部分を削除することもできます。これは、単一または二重引用符の間に何かを削除する必要があり

str = 'this is a test "this shouldn\'t be taken"'; 
str_without_quotes = str.replace(/(['"]).*?\1/g, "") // => 'this is a test ' 
+0

これは良い答えですが、文字列に改行がある場合は機能しません。 – Prestaul

2

、それは複数行の文字列(含む文字列で動作します\ nまたは\ r)と、それはまた、エスケープ引用符を処理する必要があります:

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 ' 
関連する問題