简体   繁体   中英

Convert HTML string to JavaScript text keeping indentation

I want to target or match only the first occurrence per line

Typical Scenario:

I have an HTML Structure that I am using in JavaScript.

<ul>
    <li> ABC </li>
    <li> DEF </li>
    <li> GHI <span> GHI-SPAAN </span> </li>
</ul>

To convert the above into a string, in my editor, I can simply Find & replace EOL with a '+ and beginning of line with a ' so that the code would be

var tpl = ''+
    '<ul> '+
    '<li> ABC </li> '+
    '<li> DEF </li> '+
    '<li> GHI <span> GHI-SPAAN </span> </li> '+
    '</ul> ';

But you see, I when I replace the beginning of line with '< ,当我替换行的开头'<

So I want to uniquely target (target only the first occurrence of < and replace with '< )

I am using KOMODO edit and Sublime Text 2

I'm not a KomodoEdit user, but I tried these replacements and they worked:

  • starting quote: replace ^(\\s*)< with \\1<
  • ending quote: replace >\\s*$ with >' +

Hope this helps.

Rather than converting HTML to a JS string, it would be much better to create the elements in JS and put them in the DOM. This would give you much more control, not create such a difficult to maintain/read code, and be much faster (amongst other benefits):

var outerDiv = document.createElement("div");
outerDiv.className = "spa-shell-head";

var innerDivLogo = document.createElement("div");
innerDivLogo.className = "spa-shell-head-logo";

var innerDivAcct = document.createElement("div");
innerDivAcct.className = "spa-shell-head-acct";

var innerDivSearch = document.createElement("div");
innerDivSearch.className = "spa-shell-head-search";

outerDiv.appendChild(innerDivLogo);
outerDiv.appendChild(innerDivAcct);
outerDiv.appendChild(innerDivSearch);
document.body.appendChild(outerDiv);

The above creates the following:

在此处输入图片说明

https://jsfiddle.net/yfeLbhe4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM