简体   繁体   English

正则表达式替换元素文本

[英]regex replace element text

Never seem to master those regex's... 似乎从未掌握过这些正则表达式的...

I need to update the total with newVal 我需要用newVal更新总数

<span class="myClass">some text Total (12)</span>

into 进入

<span class="myClass">some text Total (13)</span>

and also without a current value 也没有当前值

<span class="myClass">some text Total</span>

into 进入

<span class="myClass">some text Total (13)</span>

oh, and some text can be anything 哦,有些文字可以是任何东西

my code 我的密码

    newVal = 13;
    $('.myClass').text( $('.myClass').text().replace(???, ???) );

You could wrap counters with span : 您可以使用span包裹计数器:

<span class="myClass">some text Total (<span>12</span>)</span>

and do like so: 并这样做:

newVal = 13;
$('.myClass span').text(newVal);

Wrong approach, your code would only return the new string. 错误的方法,您的代码将仅返回新字符串。 To set it, use 要设置它,使用

$('.myClass').text(function(i, old){ 
   return old.replace(/(\s+\(\d+\))?$/, " ("+newVal+")");
})

The regex matches the string end, and (optionally) whitespaces + bracketed number before. 正则表达式匹配字符串结尾,并且(可选)匹配空格+之前的括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM