Imported Answer
Replace Method and URI Encoding
A debugging-focused answer about when URI encoding matters more than the replace call itself.
Problem and Solution
This page carries the full answer
Problem: A replace call looked broken, but the real issue was that the string behaved like a URI and needed the right encoding and decoding strategy.
Original question: replace() Method don't replace anything by user3944364.
Full imported answer
Updated:
var str = encodeURI(cup[number][9]);
str = decodeURI( str.replace( encodeURI('amazon®ion'), encodeURI('amazon&region') );
encodeURI() & decodeURI()
- Since it's a url, this is the favorable function
- With the use of
encodeURI('amazon®ion')you don't have to seccond guess the encoded character(s) &inamazon®ionneeds to be in the form of&, like so:amazon&region- use
decodeURI()to use the new URI
JsFiddle: http://jsfiddle.net/cbsL9ed7/2/
Want an even better and more flexible solution?
Why not make it a function then?
function updateURI(uri, oldValue, newValue) {
var str = encodeURI( uri );
str = decodeURI( str.replace( encodeURI(oldValue), encodeURI(newValue) ) );
return str;
}
var newURI = updateURI(cup[number][9], 'amazon®ion', 'amazon&region');
document.write( newURI )
jsFiddle: http://jsfiddle.net/cbsL9ed7/4/
Running Demo
Working code in-house
This demo is embedded here so the page carries the working result, not just a link away from the portfolio.
Source and Credit
Also posted on Stack Overflow
This page keeps the full solution in-house, while still pointing back to the original Stack Overflow post for proof and attribution.
Original answer: Stack Overflow answer #29685434 by Omar Juvera.
License note: this answer was originally published on Stack Overflow under CC BY-SA 3.0. Keeping a small source note here is the cleanest way to preserve attribution while the portfolio page remains the main destination.