[英]Split string with commas to new line
我有一个字符串
This is great day, tomorrow is a better day, the day after is a better day, the day after the day after that is the greatest day
我想基本上将这个长字符串拆分为逗号并插入一个新行,使其成为
This is great day
tomorrow is a better day
the day after is a better day
the day after the day after that is the greatest day
我怎样才能做到这一点 ?
var formattedString = yourString.split(",").join("\n")
如果你想让新行成为HTML换行符
var formattedString = yourString.split(",").join("<br />")
这对我来说最有意义,因为你将它分成行然后用换行符加入它们。
虽然我认为在大多数情况下速度不如可读性重要,但在这种情况下我很好奇,所以我写了一个快速的基准 。
似乎(在chrome中)使用str.split(",").join("\\n")
比str.replace(/,/g, '\\n');
更快str.replace(/,/g, '\\n');
。
你也可以替换它们:
string.replace(/,/g, '\n');
> a = 'This is great day, tomorrow is a better day, the day after is a better day, the day after the day after that is the greatest day'
> b = a.split(', ').join('\n')
"This is great day
tomorrow is a better day
the day after is a better day
the day after the day after that is the greatest day"
你可以使用.split()
创建一个包含字符串所有部分的数组......
var str = 'This is great day, tomorrow is a better day, the day after is a better day, the day after the day after that is the greatest day';
str.split(',');
-> ["This is great day", " tomorrow is a better day", " the day after is a better day", " the day after the day after that is the greatest day"]
现在,你可以用不同的部分做任何你想做的事情。 由于您想要使用新行加入,您可以使用.join()
将其重新组合在一起...
str.split(',').join('\n');
-> "This is great day
tomorrow is a better day
the day after is a better day
the day after the day after that is the greatest day"
没有在我的浏览器上测试尝试:
var MyStr="This is great day, tomorrow is a better day, the day after is a better day, the day after the day after that is the greatest day";
Var splitedStr = MyStr.split(",");
var returnStr = '';
for (var i = 0; i < splitedStr.length; i++)
{
returnStr += splitedStr[i] + '<br />';
}
document.write(returnStr);
<p id="errorMessage">Click | the |button |to |display| the| array| values|
after| the| split.</p>
$(document).ready(function () {
var str = $("#errorMessage").text();
document.getElementById("errorMessage").innerHTML=str.split("|").join("
</br>"); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.