I need to make a simple Javascript converter, which would turn <textarea>
input into html-formatted list.
This is how a sample input would look:
Brand: Brand1
Model1 /Model2 /Model3 /Model4 /Model5 /Model6 /
Brand: Brand2
Model1 /Model2 /Model3 /Model4 /Model5 /Model6 /
And this would be the html after conversion:
<h3>Brand1</h3>
<ul>
<li>Model1</li>
<li>Model2</li>
<li>Model3</li>
<li>Model4</li>
<li>Model5</li>
<li>Model6</li>
</ul>
<h3>Brand2</h3>
<ul>
<li>Model1</li>
<li>Model2</li>
<li>Model3</li>
<li>Model4</li>
<li>Model5</li>
<li>Model6</li>
</ul>
Could any one provide some sample code to do that? Thanks a lot
jQuery would be the easy way to do this, but if you're forced to do it with pure Javascript, you'll have something that looks like this:
HTML:
<textarea id="input" rows="5" cols="60">Brand: Brand1
Model1 /Model2 /Model3 /Model4 /Model5 /Model6
Brand: Brand2
Model1 /Model2 /Model3 /Model4 /Model5 /Model6
</textarea>
<input id="convertButton" type="button" value="convert" />
<div id="output"></div>
Javascript:
var convertButton = document.getElementById('convertButton');
convertButton.onclick = function(){
var input = document.getElementById('input');
var output = document.getElementById('output');
var lines = input.value.split( '\n' );
var html = '';
for( var i=0; i<lines.length; i++ ) {
if( lines[i].indexOf('Brand')===0 ) {
var brand = lines[i].split(':')[1];
html += '<h3>' + brand + '</h3>';
}
if( lines[i].indexOf('/')!==-1 ) {
var models = lines[i].split('/');
html += '<ul><li>' + models.join('</li><li>') + '</li></ul>';
}
}
output.innerHTML = html;
};
Note that this solution doesn't do a lot of error checking, and it would get pretty confused if you weren't careful with your input, but it should give you a starting place to do what you want. See a live demo here: http://jsfiddle.net/GUQXf/4/
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.