What is the most elegant way to make this kind of string array change?
If I have an array of string like:
var myStrArr=['book-in-my-house',
'chair-in-my-house',
'bed-in-my-house',
'TV-in-my-house'];
I would like to change 开发者_StackOverflowmyStrArr to herStrArr like:
var herStrArr=['book-in-her-house',
'chair-in-her-house',
'bed-in-her-house',
'TV-in-her-house'];
As you saw above, change every "my
" to "her
" in each string.
What is the most elegant way to make this change in JavaScript?
No other way than looping through. As you noted in your tags that you are using jQuery, you can use jQuery's $.map
to assist. It's not technically the most elegant solution, but one of the simplest and shortest:
var herStrArr = $.map(myStrArr, function(str) {
return str.replace('-my-', '-her-');
});
You don't have to use a loop - if you can choose a character guaranteed not to be contained in any string. For example, with "|"
you can do:
var herStrArr = myStrArr.join("|").replace(/\bmy\b/gi, "her").split("|");
To remove the word "my", I assume you mean that you want:
book-in-my-house => book-in-house
If so, then:
var strArr = myStrArr.join("|").replace(/-my\b/gi, "").split("|");
Store ['book', 'chair', 'bed', 'TV']
instead, then you don't have to do anything.
You could use jQuery $.each
function.
var myStrArr=['book-in-my-house',
'chair-in-my-house',
'bed-in-my-house',
'TV-in-my-house'];
$.each(myStrArr,function(i){ myStrArr[i] = myStrArr[i].replace('-my-','-her-');})
Live example: http://jsfiddle.net/Xx5XM/
精彩评论