使用数组中的关键字拆分Javascript-String

时间:2014-02-15 20:48:33

标签: javascript arrays split

如何使用数组关键字列表在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";
  1. 我想从每一行开出HTML段落
  2. 如果某行的开头(!)有一个关键字,关键字应该有自己的段落,并且应该删除“:”(如果有的话)。
  3. 在我的例子中,我想得到:

    <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>');
    

3 个答案:

答案 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");

http://jsfiddle.net/Tg3ch/

答案 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);
    }    
});

Fiddle

答案 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/