JavaScript String Multiple Replace
I have a small web app where I need to perform text replacement in a string. However, the normal string.replace won't work. I am modifying p开发者_开发技巧ortions of the text and then I need to put them back in the original string. For example, if I have:
var text = 'TEXT 000.99 001.00 TEXT'
and I need to add 0.01 to each of these numbers, I have an array of results:
var new_vals = [001.00, 001.01]
Then, when I try to replace 000.99 with 001.00, it will work and give me the following string:
text = 'TEXT 001.00 001.00 TEXT'
now I face the problem. The next replacement should be 001.00 <- 001.01, but doing so would result in:
text = 'TEXT 001.01 001.00 TEXT'
My question is, do you know of any JS library that provides a replace function that can perform multiple search/replace at the same time and on a copy of the string?
Use str.replace with a function:
var text = 'TEXT 000.99 001.00 TEXT';
var new_vals = ["001.00", "001.01"];
var index = 0;
//Returns a new result string
var result = text.replace(/\b([\d.]+)\b/g, function(substr, num, offset, str){
//See if the number is actually a number
var num = parseFloat(num);
//If not, return original
if(isNaN(num))
return substr;
//Return the number from new_vals and increment the index
else
return new_vals[index++];
});
//result == "TEXT 001.00 001.01 TEXT"
Or, you could do the addition in the function:
var text = 'TEXT 000.99 001.00 TEXT';
//Returns a new result string
var result = text.replace(/\b([\d.]+)\b/g, function(substr, num, offset, str){
//See if the number is actually a number
var num = parseFloat(num);
//If not, return original
if(isNaN(num))
return substr;
//Return num+0.01 with 2 decimal places
else
return (num+0.01).toFixed(2);
});
//result == "TEXT 1.00 1.01 TEXT"
Try using the global replace regexp instead of a simple string. The simple string will replace only the first matching instance.
'TEXT 001.00 001.00 TEXT'.replace(/001.00/g, '001.01');
You could try split(' ')
the values into an array. Then modifying the specific elements using a loop. Followed by join(' ')
to join the text back into a string.
精彩评论