我正在尝试编写一个Javascript函数,该函数使用1,2或3个单词的短语并返回相同的短语,但第一个找到的空格将替换为<br>
所以
Hello My World
变为
Hello<br>My World
或
Hello World
变为
Hello<br>World.
想法?
答案 0 :(得分:2)
function space2br(str, limit){
for(var i = 0; i < limit; i++)
str = str.replace(/\s/, '<br>');
return str;
}
space2br('Hello My World', 1); // "Hello<br>My World"
space2br('Hello My World', 2); // "Hello<br>My<br>World"
function firstSpace2br(str){
return space2br(str, 1);
}
firstSpace2br('Hello My Favourite World'); // "Hello<br>My Favourite World"
答案 1 :(得分:1)
尝试简单的正则表达式替换
'Hello My World'.replace(/\s/, '<br />')
答案 2 :(得分:1)
您可以将此更改为一组选项,但是对于可选的有序参数,传递空白也可以正常工作:
<div id='test'></div>
<div id='test2'></div>
<div id='test3'></div>
然后在js:
function replaceMe(sString, sTarget, sWith, nCount){
if(!sString) return 'Please provide a string';
if(!sTarget) sTarget = /\s/;
if(!sWith) sWith= '<br/>';
if(!nCount) nCount = 1;
for(var c = 0; c < nCount; c++) sString= sString.replace(sTarget, sWith);
return sString;
}
x = 'Hello Crazy World Full of People!';
y = replaceMe(x);
document.getElementById('test').innerHTML = y;
y = replaceMe(x,'','',10);
document.getElementById('test2').innerHTML = y;
y = replaceMe(x,'','',2);
document.getElementById('test3').innerHTML = y;
你知道这变得非常灵活。