【问题标题】:jquery/javascript: what is the shortest way of expressing the accessing and altering of a substring? [duplicate]jquery/javascript:表达访问和更改子字符串的最短方法是什么? [复制]
【发布时间】:2012-08-01 23:54:45
【问题描述】:

可能重复:
Use RegExp to match a parenthetical number then increment it

我已经知道如何实现该解决方案,但需要编写几行代码;我想知道是否有一种简短而聪明的方法来访问整数字符串的子字符串并递增它,其中子字符串没有包含在任何标记标签中?

/*Let's say the string is*/ "<span class="ideacount">[5 ideas]</span>"

我想增加它说“[6 个想法]”。

【问题讨论】:

    标签: javascript jquery substring increment


    【解决方案1】:

    这样的?

    var spanContent = $('#ideaCount').text();    
    var i = parseInt(spanContent.replace(/[^0-9\.]+/g, ''));
    i+=1;
    $('#ideaCount').text( spanContent.replace(/[0-9\.]+/g, i+1) );
    

    只需添加一些错误检查。

    【讨论】:

    • 在发布之前应该考虑一下,因为我想出了一个单行解决方案(减去变量声明): $(this).html(" [" + ((v = $(this ).text().match(/\d/) || 0),++v) +"idea" + (v>1?"s":"") + "]");除非有人可以让它更精简?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 2010-10-28
    • 2011-09-25
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    相关资源
    最近更新 更多