javascript正则表达式字符串替换只工作一次

ale*_*ech 0 javascript regex

问候.

我有一个功能,它监视"价格"字段的内容并更新"购物车"字段中的字符串.在"cart"字段中,字符串在|之间 字符被"价格"中输入的内容替换.我当前的功能只能工作一次,而连续的更改没有任何反应.我知道这不是事件本身的问题,因为如果我在没有正则表达式的情况下替换整个字段,它可以正常工作.

这是"购物车"字段的格式,15需要用"价格"字段中的内容替换: {nicepaypal:cart | 15 | 2010年新增}.

$('price').addEvent('keyup', function() {
    var price = $(this).value;
    var currentCartValue = $('cart').value;
    var oldPrice = String(currentCartValue.match(/\|...\|/));
    oldPrice = oldPrice.substring(1, oldPrice.length-1);  // ugly but could not get lookaheads for "between" characters to work properly
    var newCartValue = currentCartValue.replace(oldPrice, price);
    $('cart').value = newCartValue;
});
Run Code Online (Sandbox Code Playgroud)

另一种变化也不起作用:

newCartValue = currentCartValue.replace(/\|...\|/), '|'+price+'|');
Run Code Online (Sandbox Code Playgroud)

在"价格"字段中多次按键时,为什么这不起作用.谢谢.

SLa*_*aks 5

您需要将g(全局)标志添加到正则表达式.

newCartValue = currentCartValue.replace(/\|...\|/g, '|'+price+'|');
Run Code Online (Sandbox Code Playgroud)