Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jQuery为元素内部的文本应用正则表达式替换_Javascript_Jquery_Regex - Fatal编程技术网

Javascript 使用jQuery为元素内部的文本应用正则表达式替换

Javascript 使用jQuery为元素内部的文本应用正则表达式替换,javascript,jquery,regex,Javascript,Jquery,Regex,我在整个页面上都有这样的元素: <span class="am-product-terms">$49.95 for each 3 months</span> <span class="am-product-terms">$149.95 for each year</span> 这引发了一个错误,因此我尝试了以下方法: $('.am-product-terms').text().replace(/for[\s\S]+/, '') 这也不起作用。.

我在整个页面上都有这样的元素:

<span class="am-product-terms">$49.95 for each 3 months</span>
<span class="am-product-terms">$149.95 for each year</span>
这引发了一个错误,因此我尝试了以下方法:

$('.am-product-terms').text().replace(/for[\s\S]+/, '')
这也不起作用。

.replace()
返回修改后的字符串,但不更新现有文本。您需要使用返回的字符串并将其重置为输入文本

你可以用


谢谢这是我第一次看到这个。为什么需要
返回
,而在正常情况下不需要?@alexchenco
.replace()返回修改过的字符串,但不会更新现有文本。
因此,通过添加
返回
,现有的字符串将被
返回
?@alexchenco,只添加了
返回
,我使用了重载的
.text()
用于设置替换字符串的函数。
$('.am-product-terms').text().replace(/for[\s\S]+/, '')
$('.am-product-terms').text(function(_, text){
    return text.replace(/for[\s\S]+/, '');
});