简体   繁体   中英

RegEx - Find all sets of string enclosed by quotes

I have documents in which i need to highlight that a person was quoted. So I'm looking for all text that's enclosed by quotes...I'm using the below code, which works but it only captures the first occurence..

var str = 'L\'armée sud-coréenne accuse la Corée du Nord d\'avoir lancé \"plusieurs\" missiles \"balistiques interdits qui ont franchi une distance\" d\'environ 1000 kilomètres avant de tomber au \"large de la côte est du pays communiste.\" '

var reg = new RegExp(/"(.*?)"/);
var matches = str.match(reg);

for (var i = 0; i < matches.length; i++) {
    var s = matches[i];
    str = str.replace(matches[i], '<span style="color:blue">' + matches[i] + '</span>');
    matches[i] = s;
}

Make your Regex global :

The g modifier is used to perform a global match (find all matches rather than stopping after the first match).

var str = 'L\'armée sud-coréenne accuse la Corée du Nord d\'avoir lancé \"plusieurs\" missiles \"balistiques interdits qui ont franchi une distance\" d\'environ 1000 kilomètres avant de tomber au \"large de la côte est du pays communiste.\" '

var reg = new RegExp(/"(.*?)"/g); //notice /g, making the expression global
var matches = str.match(reg);

for (var i = 0; i < matches.length; i++) {
    var s = matches[i];
    str = str.replace(matches[i], '<span style="color:blue">' + matches[i] + '</span>');
    matches[i] = s;
}

document.getElementById("myDiv").innerHTML = str;

Making your expression global guarantees all instances of the quotes match.

JSFiddle: https://jsfiddle.net/zjxjub96/

To illustrate what @Casimir says in his comment, here is a little example:

 var str = 'L\\'armée sud-coréenne accuse la Corée du Nord d\\'avoir lancé \\"plusieurs\\" missiles \\"balistiques interdits qui ont franchi une distance\\" d\\'environ 1000 kilomètres avant de tomber au \\"large de la côte est du pays communiste.\\" ' str = str.replace(/"(.*?)"/g, '<span style="color:blue">$&</span>') document.getElementById("myDiv").innerHTML = str; 
 <div id="myDiv"> </div> 

Notice that this way is easier, and doesn't require a for loop.

JSFiddle: https://jsfiddle.net/zjxjub96/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM