Javascript匹配类似于sql like operator

时间:2014-07-10 03:39:16

标签: javascript jquery regex

我想做sql的所有操作'喜欢'在javascript中。例如:

var str="South-Asia, North-America, South-Africa";

var firstwordmatch=South%; //will result South-Asia,South-Africa
var last match=%ica // will match North-America, South-Africa

我尝试的是以下内容:

var ex = str.split('%')[1]; // this for matching %ica

var l = str.length;
var n = str.indexOf("%");
// this for matching %ica
if (n == 0) {                   
    var m = c.match(/(.*)ex/)
}
// this for matching 
// this for matching south%
else if (n == l - 1) {
    var m = c.match(/ex(.*)/)
}

但是我无法编写正确的正则表达式,因为它没有得到ex变量。

1 个答案:

答案 0 :(得分:0)

从南方开始:South\S+

在JS中:

var myregex = /South\S+/;
var matchArray = myregex.exec(yourString);
if (matchArray != null) {
    thematch = matchArray[0];
} else {
    thematch = "";
}

以ica结尾:\S+ica

在JS中:

var myregex = /\S+ica/;
var matchArray = myregex.exec(yourString);
if (matchArray != null) {
    thematch = matchArray[0];
} else {
    thematch = "";
}

<强>解释

  • \S+匹配任何非空白字符的字符
  • South匹配文字字符
  • ica匹配文字字符