【问题标题】:jQuery find and replace text based on key value pair objectjQuery基于键值对对象查找和替换文本
【发布时间】:2012-07-09 01:02:48
【问题描述】:

我翻遍了,发现了一些有用的帖子,用于在 jquery 中使用键值对数组/对象进行查找/搜索/替换,

但我不能让它工作,

这是网站的测试网址:

http://www.larryadowns.com.php5-1.dfw1-2.websitetestlink.com/

如您所见,这是一个包含帖子信息的博客提要。我正在尝试定位日期月份,并为每个月份进行搜索和替换以放入西班牙月份。

这里是 javascript,它都被包裹在一个 jQuery(document).ready()...

    var monthMap = {
        "January" : "Enero",
        "February" : "Febrero",
        "March" : "Marzo",
        "April" : "Abril",
        "May" : "Mayo",
        "June" : "Junio",
        "July" : "Julio",
        "August" : "Agosto",
        "September" : "Septiembre",
        "October" : "Octubre",
        "November" : "Noviembre",
        "December" : "Diciembre"
    };

    // sift thru the post-info, replacing only the month with the spanish one.
    $(".post-info .date").text(function(index, originalText) {

        var moddedText = '';

        for ( var month in monthMap ) {

            if (!monthMap.hasOwnProperty(month)) {
                continue;
            }

            moddedText = originalText.replace(month, monthMap[month]);

//            moddedText = originalText.replace( new RegExp(month, "g") , monthMap[month] );

            console.log("month : " + month);
            console.log("monthMap[month] : " + monthMap[month]);
        }

        console.log('-------------------');
        console.log('index : ' + index);
        console.log("monthMap : " + monthMap);
        console.log("originalText : " + originalText);

        console.log("moddedText : " + moddedText);

        return moddedText;
    });

但是,.replace 或带有 RegEx 的 .replace 都没有真正替换任何东西。 我哪里做错了? ty 再次堆叠。

【问题讨论】:

    标签: jquery arrays search object replace


    【解决方案1】:

    不太清楚为什么,但似乎您的代码在接下来的几个月中将moddedText 恢复为原始状态。因此,它只是正确地替换了 12 月。

    我使用了一种稍微不同的方法,但它应该会产生您正在寻找的东西。

    $(".post-info .date").text(function(index, originalText) {
    
        for ( var month in monthMap )
        {
            if (originalText.indexOf(month) > -1)
            {
                return originalText.replace(month, monthMap[month]);
            }
        }
    
        return originalText;
    });
    

    查看jsFiddle 获取完整代码和演示。

    【讨论】:

    • 最优秀。非常感谢戈兰。解决了。如果有人有这个答案,很高兴知道原因。但不用担心。
    • 没问题,很高兴能帮上忙。实际上,现在我已经喝了咖啡,这似乎很明显。因为它一直在迭代所有月份(即使在成功匹配之后),originalText 正在覆盖早先成功替换的moddedText。因此,为什么只有 12 月有效,因为它没有接下来的几个月。
    猜你喜欢
    • 2019-07-19
    • 2021-10-25
    • 2020-08-23
    • 2014-01-26
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多