Splitting Javascript-String with keywords from an array

How can I split a string in JavaScript using an array of keywords list?

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";
  • I would like to make an HTML paragraph from each line
  • If at the beginning (!) Of the line there is a keyword from the array, the keyword should get its own paragraph, and the “:” should be deleted (if there is one).

In my example, I want to get:

<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>

My bad decision right now looks like

str.trim().replace(/(.*?)(\n|:)/mgi, '<p>$1</p>');
+3
source share
3 answers

You can create a regular expression from a list of keywords:

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

For a complete example, see http://jsfiddle.net/6uuXY/1/ .

+2
source
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/

+3
source

, , , :

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

All Articles