Reputation: 656
I need to find a regular expression that would be able to work around an issue I am having.
Query: barfly london
Should match: Camden Barfly, 49 Chalk Farm Road, London, NW1 8AN
I've tried many, many regex's for this, but none have worked so far. I am considering that maybe I will need to split the search into two separate queries for it to work.
Could anyone point me in the right direction? I'm a bit new to this area.
Upvotes: 2
Views: 344
Reputation: 6957
Dominic's solution without case sensitivity. This is what I needed for my project.
var test="Camden Barfly, 49 Chalk Farm Road, London, NW1 8AN";
if ((test.toLowerCase().indexOf("barfly") != -1) && (test.toLowerCase().indexOf("london") != -1)) {
alert("Matched");
}
else {
alert("Not matched");
}
Upvotes: 0
Reputation: 19111
theString.match( new RegExp( query.replace( ' ', '\b.*\b' ), 'i' ) )
Upvotes: 0
Reputation: 8701
Check this:
var my_text = "Camden Barfly, 49 Chalk Farm Road, London, NW1 8AN, london again for testing"
var search_words = "barfly london";
String.prototype.highlight = function(words_str)
{
var words = words_str.split(" ");
var indicies = [];
var last_index = -1;
for(var i=0; i<words.length; i++){
last_index = this.toLowerCase().indexOf(words[i], last_index);
while(last_index != -1){
indicies.push([last_index, words[i].length]);
last_index = this.toLowerCase().indexOf(words[i], last_index+1);
}
}
var hstr = "";
hstr += this.substr(0, indicies[0][0]);
for(var i=0; i<indicies.length; i++){
hstr += "<b>"+this.substr(indicies[i][0], indicies[i][1])+"</b>";
if(i < indicies.length-1) {
hstr += this.substring(indicies[i][0] + indicies[i][1], indicies[i+1][0]);
}
}
hstr += this.substr(indicies[indicies.length-1][0]+indicies[indicies.length-1][1], this.length);
return hstr;
}
alert(my_text.highlight(search_words));
// outputs: Camden <b>Barfly</b>, 49 Chalk Farm Road, <b>London</b>, NW1 8AN, <b>london</b> again for testing
Upvotes: 1
Reputation: 99841
I'd suggest not using regexs if you want to search for two string literals, and instead use normal string searching twice:
var test="Camden Barfly, 49 Chalk Farm Road, London, NW1 8AN"
if ((test.indexOf("Barfly") != -1) && (test.indexOf("London") != -1)) {
alert("Matched!");
}
If you're not concerned about case-sensitivity, then you can just lowercase/uppercase your test string and your string literals accordingly.
Upvotes: 2
Reputation: 4132
Try this:
var r = /barfly|london/gi
str = "Camden Barfly, 49 Chalk Farm Road, London, NW1 8AN"
alert(str.match(r).length>1)
Upvotes: 3