将字符串拆分成JavaScript中的单词

时间:2019-07-02 11:58:41

标签: javascript regex split

我必须在JavaScript中将字符串拆分成一个单词。

var urlCurrent = "www.example.com/web/americas/home";
var siteNames = ["americas","international","europe","asia-pacific","africa-middle-east","russia","india"];
var siteNamesJoin = siteNames.join('|');
var siteUrlCurrent = urlCurrent.split(siteNamesJoin);

在这里,我必须使用数组中的单词来拆分urlCurrent字符串。因此最后我必须得到www.example.com/web/americas。我没有得到正则表达式。

3 个答案:

答案 0 :(得分:3)

您可以使用

new RegExp("^.*?(?:" + siteNamesJoin + "|$)")

图案看起来像

^.*?(?:americas|international|europe|asia-pacific|africa-middle-east|russia|india|$)

请参见regex graph

enter image description here

详细信息

  • ^-字符串的开头
  • .*?-除换行符以外的任何0个或多个字符,应尽可能少
  • (?:americas|international|europe|asia-pacific|africa-middle-east|russia|india|$)-管道之间或字符串结尾之间的任何值。

请参阅JS演示

var urlCurrent = "www.example.com/web/americas/home";
var siteNames = ["americas","international","europe","asia-pacific","africa-middle-east","russia","india"];
var siteNamesJoin = siteNames.join('|');
var match = urlCurrent.match(new RegExp("^.*?(?:" + siteNamesJoin + "|$)"));
var siteUrlCurrent = match ? match[0] : "";
console.log(siteUrlCurrent);

注意:如果siteNames“单词”可能包含特殊的正则表达式元字符,则需要转义siteNames项:

var siteNamesJoin = siteNames.map(function (x) { return x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') }).join('|');

此外,如果这些单词必须在/或字符串结尾之间匹配,则可以调整模式:

var match = urlCurrent.match(new RegExp("^(.*?)/(?:(?:" + siteNamesJoin + ")(?![^/])|$)"));

查看另一个演示。

var urlCurrent = "www.example.com/web/americas/home";
var siteNames = ["americas","international","europe","asia-pacific","africa-middle-east","russia","india"];
var siteNamesJoin = siteNames.map(function (x) { return x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') }).join('|');
var match = urlCurrent.match(new RegExp("^.*?/(?:(?:" + siteNamesJoin + ")(?![^/])|$)"));
var siteUrlCurrent = match ? match[0] : "";
console.log(siteUrlCurrent);

答案 1 :(得分:0)

也许这对您有帮助,我想您不需要正则表达式:


var urlCurrent = "www.example.com/web/americas/home";
var siteNames = ["americas","international","europe","asia-pacific","africa-middle-east","russia","india"];
var siteNamesJoin = siteNames.join('|');
var siteUrlCurrent = urlCurrent.split(siteNamesJoin);

const pos = urlCurrent.split("/")[2];
let url;

for(const index in siteNames) {
  if(pos === siteNames[index]) {
     url = urlCurrent.substring(0,urlCurrent.lastIndexOf("/"));
  }
}

console.log(url);

答案 2 :(得分:0)

使用正则表达式和匹配项

   Memberid Question Numeric Answers FreeText Answers
0         1       Q1               3                 
1         1       Q2               2                 
2         1       Q3                        Test Text
3         2       Q1               3                 
4         2       Q2               2                 
5         2       Q3                        Test Text