0

Sorry for the noob question .....

I have 2 object with strings in an array .....

 const collection = [
  {name: 'strA', value: 'Hello World'},
  {name: 'strB', value: 'World'},
 ]

I only want to replace the string value that has the entire phrase 'World'

Simply doing ....

collection.map((item) => {
  item.value.replace('World', 'Earth')
});

will undesirably change my array to ...

 const collection = [
  {name: 'strA', value: 'Hello Earth'},
  {name: 'strB', value: 'Earth'},
 ]

when in fact, what I wanted was ....

 const collection = [
  {name: 'strA', value: 'Hello World'},
  {name: 'strB', value: 'Earth'},
 ]

Any ideas?

Thanks!

2 Answers2

1

Use a regex with the start(^) and end($) anchors

const collection = [
  {name: 'strA', value: 'Hello World'},
  {name: 'strB', value: 'World'},
 ];

var result = collection.map((item) => {
  return item.value.replace(/^World$/, 'Earth')
});

console.log(result);
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • Thanks, I'll come back in a short while when the system allows me to 'thumbs' you up. –  Nov 19 '15 at 18:07
0

When you are saying

collection.map((item) => {
  item.value.replace('World', 'Earth')
});

means each item in the collection replace if it finds a word 'World' to 'Earth'.

But in this case, even the first element of the array also has the word 'World'. So if you need to modify only an item, which contains word 'World' exactly, then we should be more specific. For that we need to use regEx saying /^World$/ ^begins with 'W' and $ends with 'd'.

collection.map((item) => {
  item.value.replace(/^World$/, 'Earth')
});

Or

if you specifically want the exact index (i.e. 2nd item in the collection) to be modified, if it has word 'Earth', then

if(collection[1])  //checking not null
   collection[1] = collectioin[1].replace('World', 'Earth')
rajuGT
  • 6,224
  • 2
  • 26
  • 44