Regexp for String

How to match strings in single quote or double quotes?

var str = "abcdef" or var str = '123456' 

Regexp

Here's the regexp to match the string - 2 regexp parts seperated by | (or). The left side matches any characters except double quotes which are enclosed in double quotes and the other part matches the string in single quote.

/"[^"]*"|'[^']*'/

Let's have a test.

var re = /"[^"]*"|'[^']*'/g;
var ma = '"abc"def"123"'.match(re);

return "abc","123"

Application

What is useful with this regexp? We can use it to highlight strings which are enclosed by single quote or double quotes. Like this one,

var re = new RegExp( '^rgb\\((\\d{1,3}),\\s*(\\d{1,3}),\\s*(\\d{1,3})\\)$');

We could use replace method to add CSS style into the matched strings. Here's the code,

var str = "var re = new RegExp( '^rgb\\((\\d{1,3}),\\s*(\\d{1,3}),\\s*(\\d{1,3})\\)$');";
var re = /"[^"]*"|'[^']*'/g;
var str = str.replace(/("[^"\n]*")|('[^'\n]*')/g,'<span style="color:#c00000">$1$2</span>');
document.getElementById("aa").innerHTML = str;