Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting Javascript-String with keywords out of an array

How can I split a string in JavaScript using an array-keyword 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";
  1. I would like to make out of every line an HTML-paragraph
  2. If there is a keyword out of the array at the beginning (!) of a line, 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 poor solution right now is something like

str.trim().replace(/(.*?)(\n|:)/mgi, '<p>$1</p>');
like image 400
user3142695 Avatar asked Jan 29 '26 11:01

user3142695


1 Answers

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/

like image 123
aquinas Avatar answered Jan 31 '26 01:01

aquinas