如何使用数组关键字列表在JavaScript中拆分字符串?
var keywords = [ 'An Example', 'Test'];
var str = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr\n"+
"Test: Lorem ipsum dolor sit amet, consetetur sadipscing elitr\n"+
"This is An Example Lorem ipsum dolor sit amet, consetetur sadipscing elitr\n"+
"An Example Lorem ipsum dolor sit amet, consetetur sadipscing elitr";
在我的例子中,我想得到:
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr</p>
<p>Test</p>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr</p>
<p>This is An Example Lorem ipsum dolor sit amet, consetetur sadipscing elitr</p>
<p>An Example</p>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr</p>
我现在的糟糕解决方案就像是
str.trim().replace(/(.*?)(\n|:)/mgi, '<p>$1</p>');
答案 0 :(得分:3)
function escapeRegExp(str){
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
reg = keywords.map(function(s){ return escapeRegExp(s) + ":?";}).join("|");
var result = str.split(/\n/).map(function(x) {
var res = x.split(new RegExp("^(" + reg + ")"));
return res.length==1 ? "<p>" + res[0] + "</p>" : "<p>" + res[1].replace(/:$/,"") + "</p>\n<p>" + res[2].trim();
}).join("\n");
答案 1 :(得分:2)
这是一种方法,首先分成段落,然后循环,检查每个关键字,并将结果推回到一个新的数组中:
var result = [];
var keywords = [ 'An Example', 'Test'];
str.split('\n').forEach(function(pg) {
var any = false;
for (var keyword in keywords) {
var keyword = keywords[idx];
if (pg.indexOf(keyword) == 0) {
result.push(keyword);
var stripped = pg.substr(keyword.length);
if (stripped.indexOf(": ") == 0)
stripped = stripped.substr(2);
result.push(stripped);
any = true;
break;
}
// no keyword matched -- push the paragraph unchanged
if (!any) result.push(pg);
}
});
答案 2 :(得分:2)
您可以从关键字列表中构建正则表达式:
var result = ('<p>' + str + '</p>').replace(/\r?\n/g, '</p>\r\n<p>').replace(new RegExp('^<p>(' + keywords.map(function(x){return x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');}).join('|') + ')(?:\\:)?\\s*', 'mgi'), '<p>$1</p>\r\n<p>');
有关完整示例,请参阅http://jsfiddle.net/6uuXY/1/。