简体   繁体   中英

how to add a line break to this javascript command

okay I have a script that outpouts an array like so

document.getElementById("message").innerHTML = msg;

the result I get is

line1 line2 line3 line4

I want it to be like this

line1
line2
line3
line4

I have tried adding the in various places but just cant get it to work

my full code

<html>
<head>
<script type="text/javascript">
function textareaToArray(t){
return t.value.split(/[\n\r]+/);
}
function showArray(a){
var msg="";
for(var i=0;i<a.length;i++){
msg+= a[i]+"\n";
}

document.getElementById("message").innerHTML = msg.join("</br>");

}
</script>
</head>
<title>
Welcome To ....
</title>
<body>
<center><h1> WELCOME TO .... </h1></center>
</br>
</br>
</br>
<center><form>
<textarea rows="7" cols="60" name="alpha"></textarea>
<br>
<input type="button"
value="show array"
onclick="showArray(textareaToArray(this.form.alpha ))">
</form></center>
</br>
<div id="message"></div>
</body>
</html>

You can use join() :

document.getElementById("message").innerHTML = msg.join('<br>');

jsfiddle

Edit according to OP's comment

You don't need to loop through the array when using join:

working jsfiddle

function textareaToArray(text){
    return text.value.split(/[\n\r]+/);
}

function showArray(msg){
    document.getElementById("message").innerHTML = msg.join("<br/>");
}

Also you don't have specified a doctype... That's very important. For HTML5 use <!DOCTYPE html> .

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