alex-tech
alex-tech

Reputation: 407

javascript regex string replace works only once

Greetings.

I have a function which watches the content of "price" field and updates the string in "cart" field. In "cart" field, string between | characters gets replaced with whatever is typed in "price". My current function only works once while nothing happens on consecutive changes. I know this is not a problem with the event itself because it works fine if I replace the entire field without regex.

This is the format of the "cart" field and 15 needs to be replaced with content from "price" field: {nicepaypal:cart|15|New in 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;
});

Another variation does not work either:

newCartValue = currentCartValue.replace(/\|...\|/), '|'+price+'|');

Why is this not working when pressing a key more than once in "price" field. Thank you.

Upvotes: 0

Views: 2960

Answers (3)

MPękalski
MPękalski

Reputation: 7103

You have to be sure that you always have only 3 characters between |.

Assuming that price should always be a number (maybe a float), couldn't you change that to

newCartValue = currentCartValue.replace(/\|\d+\.*\d*\|/g, '|'+price+'|');?

If you do not want to check for the number try this

newCartValue = currentCartValue.replace(/\|.*?\|/g, '|'+price+'|');

The ? after .* is crutial, as it makes sure it matches all characters between |, and no | will be found inside.

Upvotes: 2

Oliver Moran
Oliver Moran

Reputation: 5157

String.replace will only replace the first instance by default. This can be changed by use of the global (g) flag when using a regex. See use of the g flag below in the first example.

// replace globally
var str1 = "A man is a man is a man."
str1 = str1.replace(/man/g, "woman");
alert(str1);

// replaced only once
var str2 = "A dog is a dog is a dog."
str2 = str2.replace("dog", "cat");
alert(str2);

Upvotes: 2

SLaks
SLaks

Reputation: 887275

You need to add the g (Global) flag to the regex.

newCartValue = currentCartValue.replace(/\|...\|/g, '|'+price+'|');

Upvotes: 5

Related Questions