字符串中的多个搜索模式

时间:2018-01-26 04:50:05

标签: javascript

我在下面的代码中搜索了一串搜索字符串_search_ * matched。

我想知道是否有更简单的方法可以在indexof中添加多个搜索字词?那可能吗?

我的目标:只需添加变量字符串:

string_search4,5,6等等..

string =  "this is a .bigcommerce.com site";

var string_search1 = 'cdn.shopify.com/s';
var string_search2 = '.bigcommerce.com/';
var string_search3 = 'woocommerce/';

// start checkig with SHOPIFY first
var s = string.indexOf(string_search1 );
var found_s = String(s);

  // IF FOUND - look for the full url hubspot - like the mp4 url
if (found_s != '-1') {
  var result = 'SHOPIFY'
  return result;  
}
// if NOT FOUND, check with BIGCOMMERCE
else {
  var b = html.indexOf(string_search2);
  var found_b = String(b);
  if (found_b != '-1') {
    var result = 'BIGCOMMERCE'
    return result;     
  }
  else {
    var w = html.indexOf(string_search3);
    var found_w = String(w);
    if (found_w != '-1') {
      var result = 'WOO COMMERCE'
      return result;     
    }    
    else {
      var result = 'CANNOT INDENTIFY CMS'
      return result
    }
  }        
}

1 个答案:

答案 0 :(得分:0)

这可能看起来有点长,但是非常容易扩展。

// Our "key" object and defaults
var sObj = function(id){
    this.id = id;
    this.found = false;
};
// Our self-contained object with search and result
// functions. This is were and how we can expand quickly
var s = {
    'ob': [],
    'find': function(haystack) {
        if (this.ob) {
            for(var x in this.ob) {
                this.ob[x].found = (haystack.indexOf(this.ob[x].id) > -1);
            }
        }
    },
    'result': function() {
        var r = "";
        if (this.ob) {
            for(var x in this.ob) {
                if (this.ob[x].found) {
                    r += ","+this.ob[x].id;
                }
            }
        }
        return (r == "") ? r : r.substr(1);
    }
};

// Create the object array with the "id"
// Add as many as you want.
s.ob.push(new sObj('shopify.com'));
s.ob.push(new sObj('bigcommerce.com'));
s.ob.push(new sObj('woocommerce.com'));

// quick debug for testing
//for(var x in s.ob) {
//    console.log('x:['+ x +']['+ s.ob[x].id +']['+ s.ob[x].found +']');
//}

// Our string to be tested
var data = "this is a .bigcommerce.com site";

// check if the data matches one of the sObj ids
s.find(data);

// get the results
console.log('result:['+ s.result() +']');

// And for a second test (2 results)
data = "can you shopify.com or woocommerce.com me?";
s.find(data);
console.log('result:['+ s.result() +']');