用句点jQuery代替逗号

Replace comma with period jQuery

本文关键字:句点 jQuery      更新时间:2023-09-26

我需要将每个<li>值中的逗号替换为句号。

我不知道我的代码有什么问题。我检查了控制台,但是没有…

$('#stats li').each(function () {
    $(this).text().replace(/,/g, '.');
});

此代码应针对<ul id="stats">中的每个<li>。然后将<li>中的,替换为.

我也试过这个:

$('#stats li').each(function () {
        var comma = /,/g;
        if(comma.test($this)) {
            $(this).replace(comma, '.');
        }
});

我试了这个:

$('#stats li').each(function () {
    var stats = [];
    stats.push($(this).text());
    stats.replace(/,/g, '.');
    console.log(stats);
});

问题是replace方法返回一个新字符串。它不修改现有的字符串。试试这个:

$('#stats li').each(function () {
     $(this).text($(this).text().replace(/,/g, '.'));
});

但是对于这个问题,jQuery的text方法也接受一个函数。这是一个批次清洁器:

$('#stats li').text(function (index, text) { 
    return text.replace(/,/g, '.');
});