簡體   English   中英

替換下一個出現的字符串

[英]Replace next occurrence of a string

我在玩耍,試圖為將來在我有想法的項目中使用某些東西。 但是,我似乎無法使其正常運行。 我確信這不是最好的方法,但這是我能想到的唯一方法。 因此,這可能就是為什么我也無法使其正常工作的原因。

問題:問題是該函數不能替換多個現有單詞的字符串中出現的下一個單詞。 相反,它返回到字符串中第一個相同的單詞。 我從這里嘗試了一些RegExp解決方案,但未能使其正常工作。

應該做什么? 只是循環瀏覽每個單詞並突出顯示它一會兒。 它應該使用generateTime數組為每個單詞設置不同的循環時間。 稍后,最有可能是一個JSON對象。

CodePen演示/示例

這只是JS代碼:

var // ->
textElement     = $( '.text' ),
contentReplace  = textElement.text().replace( /[^\w ]/g, '' ).split( /\s+/ ),
generateTime    = [],
inc             = 0,
interval        = false;

// Generate random time
for ( var i = 0; i <= contentReplace.length; i++ ) {
    generateTime.push( Math.random() * (1 - 0.1) + 0.1 );
}

// Interval for looping trough words
var ticker = setInterval(function () {
    if ( inc == ( generateTime.length - 2 ) ) {
        clearTimeout( ticker );
    }

    if ( ! interval ) {
        setTimeout(function () {
            textElement
                .html( textElement.text().replace(contentReplace[inc], '<span>' + contentReplace[inc] + '</span>') );

            inc++;
            interval = false;
        }, generateTime[inc] * 1000);    
    }

    interval = true;
}, 500);

如果有人可以幫助我解決這個問題,

您需要跟蹤最后匹配的索引。 嘗試這個:

 var // -> textElement = $( '.text' ), contentReplace = textElement.text().replace( /[^\\w ]/g, '' ).split( /\\s+/ ), generateTime = [], inc = 0, interval = false; lastIndex = 0; // Generate random time for ( var i = 0; i <= contentReplace.length; i++ ) { generateTime.push( Math.random() * (1 - 0.1) + 0.1 ); } // Interval for looping trough words var ticker = setInterval(function () { if ( inc == ( generateTime.length - 2 ) ) { clearTimeout( ticker ); } if ( ! interval ) { setTimeout(function () { var text = textElement.text(); textElement .html( text.substr( 0, lastIndex ) + text.substr( lastIndex, text.length ).replace( contentReplace[inc], function ( match, index ) { lastIndex = lastIndex + index + match.length; return '<span>' + contentReplace[inc] + '</span>' })); inc++; interval = false; }, generateTime[inc] * 1000); } interval = true; }, 500); 
 body { font-family: "Helvetica"; padding: 25px; text-align: center; } span { background-color: #c22; color: #fefefe; padding: 8px; border-radius: 3px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="text">Lets try to make it work. Try, then try again and once again - try.</div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM