【问题标题】:Finding and replacing string if present in a JSONObj Javascript如果 JSONObj Javascript 中存在,则查找和替换字符串
【发布时间】:2013-11-25 09:22:59
【问题描述】:

我有一个包含各种元素的 JSONObj。我想对该对象的文本数据执行Regex(或某种类型的搜索)并找到各种字符串,并将它们替换为其他一些文本,例如,我想将字符串“content”替换为字符串“@ 987654321@" :

description = jsonObj.channel.item[jsonCounter].description.replace(/\/content/g, "http://www.example.com/content");

这很好用,但我想先检查一个字符串是否存在,然后替换它,我试过了:

if (holder.indexOf("about-us") !== -1) {
  description = jsonObj.channel.item[jsonCounter].description.replace(/\/about-us/g, "http://www.example.com/about-us");
} else {
  description = jsonObj.channel.item[jsonCounter].description.replace(/\/content/g, "http://www.example.com/content");
}

但这似乎不起作用。谁能帮我解决这个问题?

【问题讨论】:

  • 什么是holder 变量?什么不起作用?如果部分或其他部分,它会去。
  • holder 是我的 JSONObj 转换为字符串 :var holder = jsonObj.toString();
  • 另外,语句的 if 部分永远不会触发,即使它应该触发。
  • 试试:if (holder.indexOf("about-us") > 0)条件
  • 如果我使用该方法会出现相同的结果,不过感谢您的建议

标签: javascript regex json


【解决方案1】:

如你所说 holder 是我的 JSONObj 转换为字符串:

 var holder = jsonObj.toString(); 

var holderJSON = {url:"http://www.example.com/about-us"}

alert(holderJSON.toString()); **// this returns [Object Object]**

if (holder.indexOf("about-us") !== -1) **// is never true.**

希望这会有所帮助!

【讨论】:

  • 我应该如何将 JSON 转换为字符串呢?或者检查 JSON 中是否有类似文本的字符串?
  • var holderJSON = {url:"example.com/about-us"} var url = holderJSON.url.toString() alert(url !== -1) // 返回 true
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 2011-08-22
  • 2018-06-02
相关资源
最近更新 更多