【问题标题】:How to replace characters in JavaScript [closed]如何替换 JavaScript 中的字符 [关闭]
【发布时间】:2016-03-30 21:33:57
【问题描述】:

我有一个类似的字符串

var content = '<img id="product-collection-image-515" src="http://www.dressbd.com/media/catalog/product/cache/1/small_image/300x300/9df78eab33525d08d6e5fb8d27136e95/r/u/shirt.jpg" alt="Shirt"></img>';

我想像下面这样改变它。

var content = '<img id="product-collection-image-515" src="https://www.dressbd.com/media/catalog/product/cache/1/small_image/300x300/9df78eab33525d08d6e5fb8d27136e95/r/u/shirt.jpg" alt="Shirt"></img>';

我想使用 JavaScript 将“http”替换为“https”。我使用了.replace(),但它不起作用。

我该怎么做?谢谢

【问题讨论】:

  • 在您的问题中,您提到您使用了.replace() 函数,但这不起作用,但您忘记向我们展示您的代码。所以很难说你做错了什么。
  • 您能否提供整个代码来检查,因为 replace() 通常用于此任务
  • 不要使用正则表达式修改 HTML。相反,如果 HTML 在 DOM 中,则修改 img 元素的 src 属性。
  • @torazaburo,实际上这个 HTML 是以纯字符串的形式出现的。如果我使用typrofcontent,我得到string。我认为这是问题所在。我必须在这里做一些特别的事情。
  • 你打算用这个字符串做什么?如果您打算将其插入到 DOM 中,则将其插入,然后使用标准 DOM 函数(例如 setAttribute)对其进行修改。

标签: javascript string replace


【解决方案1】:

你的意思是这样吗?像replace()一样工作

var content = '<img id="product-collection-image-515" src="http://www.dressbd.com/media/catalog/product/cache/1/small_image/300x300/9df78eab33525d08d6e5fb8d27136e95/r/u/shirt.jpg" alt="Shirt"></img>';

var newContent = content.replace('http','https');

alert(newContent)

【讨论】:

  • 我试过了,还是不行。
  • 单击Run code snippet 上方的按钮,您将看到使用https 的URL 的警报 - 如果它不适合您,则说明其他问题
  • @Erik-JanWestendorp 请停止建议在字符串文字中添加换行符的编辑。这在 JS 中无效。我回滚了编辑。
【解决方案2】:

我通常使用.split() 例如.split("//")

var p = content.split("//");
p[0] += "s";
var result = p[0] + p[1];

【讨论】:

    【解决方案3】:

    如果替换功能对您不起作用,则可能是您没有将返回值分配给新变量。

    例如你不能这样做:

    content.replace('http','https')
    

    由于该函数返回结果并且实际上并没有改变“内容”字符串。

    相反,您需要这样做:

    var newvar = content.replace('http','https');
    

    但是,您可能根本不需要任何代码。

    在 url 前面使用 // 将指示浏览器使用与当前页面相同的协议。例如,如果从

    查看
    https://example.com/mypage
    

    这个链接

    //google.com/somestuff.js
    

    被请求为

    https://google.com/somestuff.js
    

    而如果你在一个普通的 http 网站上,链接将被请求为

    http://google.com/somestuff.js
    

    如果您尝试将混合内容(http 和 https)加载到页面中,浏览器会抱怨安全问题,因此最好使用 // 格式。

    【讨论】:

      【解决方案4】:

      试试这个

      var str = "Hi William How are You?",
          res = str.replace("William", "Anderson");
      alert(res);

      结果将是:

      Hi Anderson How are You?
      

      【讨论】:

      • 我试过了,还是不行。
      猜你喜欢
      • 2021-06-16
      • 1970-01-01
      • 2016-04-26
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      相关资源
      最近更新 更多