Transform text menu to HTML links in JavaScript
I'm transforming a text only menu / command structure into HTML links in JavaScript. The text spans that I receive are of the form:
<span>1. First option 2. Second option </span> <span>3. Third option </span>
I'd like a link for each menu item, with the link text being 'First option', 'Second option', etc. The main problem is that the spans have white-space: pre on them, and I need to retain all the spaces within the span. That is, the length of the text within each span cannot change.
I've been able to create the links with regular expressions using subpatterns and the replace method, but I can't seem to both not select the entire span, and also not have the white-space in the subpattern. This is what I had that does get both links in the same span separated, but leaves in the spaces: /(\d*)\.\s*([a-zA-Z][a-zA-Z\s]*)/g
using jquery:
var links='';
$('span').each(function(){
var text = this.innerText.replace(" ","");
var a= '<a href="#">' + text + '</a>';
links += a;
});
$('span').parent().html(links);
I had to learn negative lookahead:) Here's what I got:
/((\d+).\s)((?:[^\d\s]|\s(?!(?:\s*\d*.)|(?:\s*$))|\d(?!(?:\d*.\s)))*)/g
$1 contains the '1. ', $2 contains the '1', $3 contains the menu text. It works pretty good actually.
精彩评论