0

1、2、または 3 単語のフレーズを受け取り、同じフレーズを返す Javascript 関数を作成しようとしていますが、最初に見つかったスペースは<br>

それで

Hello My World

になる

Hello<br>My World

また

Hello World

になる

Hello<br>World.

アイデア?

4

3 に答える 3

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"
于 2013-08-26T16:12:39.397 に答える
1

これを一連のオプションに同様に変更できますが、空白を渡すと、オプションの順序付けされたパラメーターでも問題なく機能します。

http://jsfiddle.net/MHRbF/

<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;

これがどのように非常に柔軟になるかがわかります。

于 2013-08-26T16:33:56.287 に答える