6 February 2014
The problem: You have a string where you need to replace or remove a certain character inside it, for example a comma, or a forward slash. Using: $(this).replace(’,’,’‘) does not work as it only removes the first comma/forward slash. For example:
123,000,222,111
With this number it will only remove the first comma.
The solution: We want to write a function where we can easily remove all commas in a string. A way to do this is to use the split() function, this splits your string, based on the commas, into an array. We will then concatenate all the indexes of the array back into a string with no commas. The code:
var theString = '123,000,222,111'; var turnStringIntoAnArray = theString.split(','); var mergeArrayBackIntoString = ''; for (var index=0; index < turnStringIntoAnArray.length; index++){ mergeArrayBackIntoString += turnStringIntoAnArray ; }
The function:
function replaceCommas(amount){ var amountArray = amount.split(','); var amountWithoutCommas=''; for(var index=0;index
What we can use this for: We can use this function to format prices e.g. £123,000,222,111. Also we can use it for URLs and breaking apart each individual part of a URL into an array and then manipulating that in whatever way. A neat little function.