如果在使用JavaScript
的特定字符后字符串中没有空格,如何使用连续长字符串添加空格例如字符串是
Helocsdnsajdnsajndjksandjks addwdwdwdnsajkkwfjnwkjqnf wkjnfkjewnfefewfefewdd
我们想要10个字符后的空格
结果应为
Helocsdnsa jdnsajndjk sandjks addwdwdwdn sajkkwfjnw kjqnf wkjnfkjewn fefewfefew dd
答案 0 :(得分:3)
您可以使用/([^ ]{10})/g
.replace()
方法在每10个字符后添加空格。试试这个:
var str = "Helocsdnsajdnsajndjksandjks addwdwdwdnsajkkwfjnwkjqnf wkjnfkjewnfefewfefewdd";
str = str.replace(/([^ ]{10})/g, "$1 ");
console.log(str)
答案 1 :(得分:1)
这也可以完成这项工作。如果有人可以对其进行更多自定义,则此代码可以帮助...
function SplitString(str, charLimit) {
var arrData = str.split(" ");
var returnStr = '';
if (arrData.length > 0)
{
for (var i = 0; i < arrData.length; i++)
{
if (arrData[i].length > charLimit)
{
var element = arrData[i];
var element2 = '';
var loopTimes = Math.ceil(arrData[i].length / charLimit);
var pickPlace = 0
for(var j = 0;j<loopTimes;j++)
{
if (j == (loopTimes - 1)) {
element2 = element2 + element.substring(pickPlace, element.length);
}
else
{
element2 = element2 + element.substring(pickPlace, (pickPlace + charLimit)) + ' ';
}
pickPlace = pickPlace + charLimit;
}
arrData[i] = element2;
}
}
for (var i = 0; i < arrData.length; i++)
{
returnStr = returnStr + arrData[i] + ' ';
}
returnStr = returnStr.substring(0,returnStr.length-1);
return returnStr;
}
}