1

私は次のコードを持っています:

<table>
<th class="title2">The <i>very</i> hungry school</th><br />
<th class="title2">The very hungry school <span>yeah it works</span></th>

と..

    function capitalise(str) {
        if (!str) return;
        var counter = 0;
        var stopWords = ['a', 'an', 'and', 'at', 'but', 'by', 'far', 'from', 'if', 'into', 'of', 'off', 'on', 'or', 'so', 'the', 'to', 'up'];
        str = str.replace(/\b\S*[a-z]+\S*\b/ig, function(match) {
            counter++;
            return $.inArray(match, stopWords) == -1 || counter === 1 ? match.substr(0, 1).toUpperCase() + match.substr(1) : match;
        });
        return str;
    }


    $('th.title2').each(function() {    

        var capclone = $(this).clone().children(':not(i)').remove().end();

        capclone.text(capitalise(capclone.text()));

        capclone.append($(this).children(':not(i)'));

        $(this).replaceWith(capclone);

    });​

このコードは、私が必要としていることに対して機能しますが、イタリック要素を維持する方法があります。削除された時点では、それは悪い解決策ではありませんが、完璧ではありません。

4

1 に答える 1

1

text()使用する代わりに、html()それが要素である html を取得してから、各単語を大文字にします。/\b\w+\b/ig単語境界の後に 1 つ以上の文字と単語境界が続く正規表現を少し単純化しました。これは、html タグの最初の文字にも一致しますが、問題は発生しません。ノードのクローンを作成して置き換える代わりに、HTML を更新するだけで、DOM インタラクションが軽くなるため、高速になるはずです。

function capitalise(str) {
    if (!str) return;
    var stopWords = ['a', 'an', 'and', 'at', 'but', 'by', 'far', 'from', 'if', 'into', 'of', 'off', 'on', 'or', 'so', 'the', 'to', 'up'];
    str = str.replace(/\b\w+\b/ig, function(match) {
        return $.inArray(match, stopWords) == -1 ? match.substr(0, 1).toUpperCase() + match.substr(1) : match;
    });
    return str;
}

$('th.title2').each(function() {
    var capclone = $(this), newHtml = capitalise(capclone.html());
    capclone.html(newHtml);
});​

このフィドルのコードで遊ぶことができます。

于 2012-02-23T10:38:14.753 に答える