【问题标题】:Javascript search and replace not workingJavascript搜索和替换不起作用
【发布时间】:2016-05-04 07:24:28
【问题描述】:

我有一个这样的字符串,

"<?xml version="1.0" encoding="utf-8"?><feed xml:base="https://9999.example.com.us/_vti_bin/MYServices/MYServices.svc/ ... so on .....

我希望它是这样的,

"&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;feed xml:base="https://9999.example.com.us/myPart/myPart123/_vti_bin/MYServices/MYServices.svc/ ... so on

这些是大型 xml Odata 响应,我正在尝试像上面那样替换基本 url,我试过了,但它不起作用,

String.prototype.replaceAll = 函数(查找、替换){ var str = 这个; return str.replace(new RegExp(find.replace(/[-/\^$*+?.()|[]{}]/g, '\$&'), 'g'), 替换); };

string = '<?xml version="1.0" encoding="utf-8"?><feed xml:base=https://9999.example.com.us/_vti_bin/MYServices/MYServices.svc';
string = string.replaceAll('<?xml version="1.0" encoding="utf-8"?><feed xml:base=https://9999.example.com.us/_vti_bin/MYServices/MYServices.svc',
'<?xml version="1.0" encoding="utf-8"?><feed xml:base=https://9999.example.com.us/myPart/myPart123/_vti_bin/MYServices/MYServices.svc');
$('#result').html(string);

更新

我只想将这部分添加到 url,“/myPart/myPart123/”

http://jsfiddle.net/cdbzL/509/

【问题讨论】:

    标签: javascript xml


    【解决方案1】:

    也许这个示例会对您有所帮助:

    var xml = '<?xml version="1.0" encoding="utf-8"?><feed xml:base="https://9999.example.com.us/_vti_bin/MYServices/MYServices.svc/';
    
    xml.replace(/_vti_bin/img, 'myPart/myPart123/_vti_bin');
    

    您只能使用replace() 函数来执行此操作。 Read more about It.

    并将$('#result').html(string) 替换为$('#result').text(string)

    关于你的String.prototype.replaceAll = function() {}的一些话:

    Object-Oriented JavaScript - Second Edition:通过原型扩充内置对象是一项强大的技术,并且 你可以用它以任何你喜欢的方式来塑造 JavaScript。由于其 但是,您应该始终彻底考虑您的选择 在使用这种方法之前。原因是一旦你知道 JavaScript,您希望它以相同的方式工作,无论哪种方式 您正在使用的第三方库或小部件。修改核心对象 可能会使您的代码的用户和维护者感到困惑并创建 意外错误。

    Demo

    【讨论】:

    • 我接受你的回答,但稍后我会在我的系统上测试它,谢谢
    猜你喜欢
    • 2016-06-19
    • 2011-02-20
    • 2010-10-05
    • 2013-08-28
    • 2020-11-15
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多