IE issue with REGEX
Weirdness with $0.00 in string
by Amy L
HTML
<input id="string1" value="I have %1 in the bank" type="text" />
<input id="string2" value="and %1 at home and %2 missing." type="text" />
<button>Replace with $</button>
<h5>Replaced:</h5>
<div id="output"></div>
CSS
input {
width: 200px;
}
#output {
border: 1px solid grey;
padding: 5px;
}
JavaScript
function strReplace(originalStr, replacement) {
var str = originalStr || '';
var regex;
var _checkReplacementStr = function (str) {
// in IE, a single $ has special meaning, so use $$ to for '$'
return (str && str[0] === '$') ? '$' + str : str;
};
if (typeof replacement !== 'array') {
str = str.replace(/%1/g, _checkReplacementStr(replacement));
} else {
for (var i = replacement.length - 1; i >= 0; i--) {
var replacementStr = _checkReplacementStr(replacement[i]);
regex = new RegExp('%' + (i + 1), 'g');
str = str.replace(regex, replacementStr);
}
}
return str;
}
$('button').click(function () {
var str1 = $('#string1').val();
var str2 = $('#string2').val();
var replaced = strReplace(str1, '$0.00') + ' ' + strReplace(str2, ['$0.00', '$1.00']);
$('#output').html(replaced);
}).click();