问题
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 loose the indentation 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
回答1:
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.
回答2:
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/
来源:https://stackoverflow.com/questions/10310279/convert-html-string-to-javascript-text-keeping-indentation