Javascript搜索和替换无法正常工作

时间:2016-05-04 07:24:28

标签: javascript xml

我有一个像这样的字符串,

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

我希望它是这样,

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

这些是大型的xml Odata响应,我正在尝试替换上面的基本网址,我试过这个但是它没有工作,

String.prototype.replaceAll = function(find,replace){     var str = this;     return str.replace(new RegExp(find.replace(/ [ - / \ ^ $ * + ?.()| [] {}] / g,&#39; \ $&amp;&#39;),&# 39; g&#39;),替换); };

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

更新

我只想将此部分添加到网址,&#34; / myPart / myPart123 /&#34;

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

1 个答案:

答案 0 :(得分:0)

也许此示例可以帮助您:

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