JavaScript-当整个文本包含时替换

JavaScript - replace when ENTIRE text contains

本文关键字:包含时 替换 文本 JavaScript-      更新时间:2023-09-26

很抱歉收到noob问题。。。。。

我有两个数组中有字符串的对象。。。。。

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

我只想替换具有整个短语"世界"的字符串值

简单地做。。。。

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

会不希望地将我的数组更改为。。。

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

而事实上,我想要的是。。。。

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

有什么想法吗?

谢谢!

使用带有起始(^)和结束($)锚点的正则表达式

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);

当你说时

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

collection替换中的每个item,如果它找到一个单词"世界"到"地球"。

但在这种情况下,即使是数组的第一个元素也有单词"World"。所以,如果你只需要修改一个项目,其中确切地包含单词"世界",那么我们应该更具体。为此,我们需要使用regEx,即/^World$/ ^以"W"开头,$以"d"结尾。

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

如果你特别想修改确切的索引(即集合中的第二个项目),如果它有单词"地球",那么

if(collection[1])  //checking not null
   collection[1] = collectioin[1].replace('World', 'Earth')