简体   繁体   English

javascript-如何加入2个具有换行符的字符串?

[英]javascript - How do I join 2 strings that have line breaks?

lets take the string 让我们把弦

ABC  
DEF  

and join it with 并加入

123  
456

I should get 我应该得到

ABC123  
DEF456  

but instead I get 但是我得到了

ABC  
DEF123  
456

the code I used: 我使用的代码:

javascript : javascript

var strings = "ABC\nDEF" + "123\n456"  
console.log(strings)

any help here? 这里有什么帮助吗?

Try this: 尝试这个:

var str1 = "ABC\nDEF",
    str2 = "123\n456",
    str1ToArray = str1.split("\n"),
    str2ToArray = str2.split("\n"),
    result = "";
for (var i = 0; i < str1ToArray.length; i++) {
    result += str1ToArray[i];
    //Check if the second string was at least as long as the first one
    if (str2ToArray.length > i) result += str2ToArray[i];
    result += "\n";
}
//If the second string was longer than the first one, append its last values
for (var j = i; j < str2ToArray.length; j++) {
    result += str2ToArray[j] + "\n";
}
alert(result);

Math.max() to the rescue: 抢救Math.max()

 var i; var a = 'ABC\\nDEF\\nGHI'; var b = '123\\n456'; var aLines = a.split('\\n'); var bLines = b.split('\\n'); var cLines = []; var l = Math.max( aLines.length, bLines.length ); for (i = 0; i < l; i++) { cLines.push((aLines[i] || '') + (bLines[i] || '')); } document.write( '<pre>' + cLines.join('\\n') + '</pre>' ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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