Joseph Thomas
Joseph Thomas

Reputation: 157

HTML Replace Script only replacing first term

I have this script running on a Japanese directory, working to replace English terms on the page for a Blog add-on for the terms that were not customizable. It works great but it only seems to replace the term the first time it sees it.

http://www.martyregan.com/jp/blog/

For example you'll see View Post, Tags, Feb are still in English on the bottom Blog Post.

Here's the script:

$(document).ready(function(){
            $('#pb_sidebar, #left-sidebar-inner, #pb_body, #main-content-inner, #sidebar-archives').each(function(i){
$(this).html($(this).html().replace('Category List','ブログテーマ一覧'));
$(this).html($(this).html().replace('Tag List','タグ'));
})
    })

How can I alter it so that it grabs the term everywhere it sees it? Thanks!

Upvotes: 2

Views: 161

Answers (4)

Jason M. Batchelor
Jason M. Batchelor

Reputation: 2951

You're really battering the DOM with this approach, by the way.

Consider caching the .html() results, then running your replacements on that, first, before putting the new text back in the DOM:

$(document).ready(function(){
    $('#pb_sidebar, #left-sidebar-inner, #pb_body, #main-content-inner, #sidebar-archives').each(function(i){
        var mycontent = $(this).html();
        mycontent = mycontent.replace(/Category List/g,'ブログテーマ一覧');
        mycontent = mycontent.replace(/Tag List/g,'タグ');
        $(this).html(mycontent);
    })
})

Upvotes: 3

DarkAjax
DarkAjax

Reputation: 16223

Try adding a global modifier to your replace:

$(this).html($(this).html().replace(/Category List/g,'ブログテーマ一覧'));
$(this).html($(this).html().replace(/Tag List/g,'タグ'));

Upvotes: 1

grobmotoriker
grobmotoriker

Reputation: 479

As far as I know, replace is a native JavaScript function. In order to let it replace every occurence, you'll have to use the g-Parameter for the RegEx you're searching for, example /searchstring/g instead of "searchstring"

Upvotes: 1

Lloyd
Lloyd

Reputation: 29668

You need to use regex with the /g option that will repeat otherwise string.replace() only runs once.

For example:

$(this).html($(this).html().replace(/Category List/g,'ブログテーマ一覧'));

Upvotes: 5

Related Questions