Javascript .replace on Euro symbol (special characters)

1.8k views Asked by At

I am trying to replace a euro symbol with a sterling symbol using the .replace method. Unfortunately it fails with , &euro and \u20AC and the escaped versions.

Am i missing something or is replace unable to handle special characters?

function updateCurrency(elem){
    if(elem.value === 'sterling'){
        window.currency= '£';
        minValue= document.getElementById('min').value;
        minValue= minValue.replace('/€', '£');
        console.log(minValue)
        maxValue= document.getElementById('max').value.replace('\u20AC', '£');
    } else {
        window.currency= '\u20AC';
        minValue= document.getElementById('min').value.replace('£', '\u20AC');
        maxValue= document.getElementById('max').value.replace('£', '\u20AC');
    }

}

codepen: http://codepen.io/ambrosedheffernan/pen/PqOmMG

1

There are 1 answers

3
sergioFC On BEST ANSWER

Simply change your updateCurrency function for this simpler one and you'll see that and £ are replaced (when switching between currencys):

function updateCurrency(elem){
    if(elem.value === 'sterling'){
        var newCurrency = '£';
        var oldCurrency = '€';
    }
    else {
        var newCurrency = '€'; 
        var oldCurrency = '£';         
    }

    var maxValue = document.getElementById('max').value;
    maxValue = maxValue.replace(oldCurrency, newCurrency)
    document.getElementById('max').value = maxValue;

    var minValue = document.getElementById('min').value;
    minValue = minValue.replace(oldCurrency, newCurrency)
    document.getElementById('min').value = minValue;   
}