繁体   English   中英

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

[英]Javascript search and replace not working

我有这样的字符串,

"<?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响应,我正在尝试替换上面的基本URL,我试过这个,但它不起作用,

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

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

更新

我只想将此部分添加到网址“/ myPart / myPart123 /”

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

也许这个样本会帮助你:

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()函数来执行此操作。 阅读更多关于它

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

关于String.prototype.replaceAll = function() {}一些String.prototype.replaceAll = function() {}

面向对象的JavaScript - 第二版 :通过原型扩充内置对象是一种强大的技术,您可以使用它以任何您喜欢的方式来构建JavaScript。 但是,由于它的强大功能,在使用这种方法之前,您应该始终彻底考虑您的选择。 原因是,一旦你了解JavaScript,无论你使用的是哪个第三方库或小部件,你都希望它的工作方式相同。 修改核心对象可能会使代码的用户和维护者感到困惑并产生意外错误。

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM