请教正则有办法replace指定个数吗

renzaijiang 2010-01-08 11:32:26
如果设置全局参数就是全部 否则是一个 如何是指定数目
...全文
94 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
renzaijiang 2010-01-10
  • 打赏
  • 举报
回复
antony1029 2010-01-09
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 wcwtitxu 的回复:]
JScript code// 修改 String.prototype.replace(function () {var method= String.prototype.replace
String.prototype.replace=function(regex, evaluator, frequency) {if (!(frequency>0))return method.apply(?-
[/Quote]
顶!!!
dh20156 2010-01-08
  • 打赏
  • 举报
回复
可以在replace函数里自己限制,如:


<script type="text/javascript">
/* 替换两次ha为wa */
var s = 'hahahaha';
var l = 0;
var s2 = s.replace(/(ha)/ig,function(a,b){if(b&&l<2){l++;return 'Wa';}else{return b;}});
alert(s2);
</script>
真哥哥 2010-01-08
  • 打赏
  • 举报
回复
指定个数没试过,你可以把要replace的元素截取出来嘛!
sohighthesky 2010-01-08
  • 打赏
  • 举报
回复

String.prototype.replaceCount=function(reg,rep,count) {
var i=0,str=String(this);
while(str!=(str=str.replace(reg,rep)) && (++i<count));
return str;
};
var str="heillo ,this is my is dd hh is3 not my is is";
str=str.replaceCount(/(is)/,function($,$1) {
return String($1).toUpperCase();
},3)
alert(str);
wcwtitxu 2010-01-08
  • 打赏
  • 举报
回复


// 修改 String.prototype.replace
(function () {
var method = String.prototype.replace
String.prototype.replace = function(regex, evaluator, frequency) {
if (!(frequency > 0)) return method.apply(this, arguments);
var count = 0;
return method.call(this, regex, function() {
return (count++ >= frequency) ? arguments[0] :
(evaluator instanceof Function) ? evaluator.apply(null, arguments) : evaluator;
});
};
})();


var s = "aaaaaaa";

WScript.Echo( s.replace(/a/g, "A") );
WScript.Echo( s.replace(/a/g, "A", 2) );

var i = 0;
WScript.Echo( s.replace(/a/g, function(){return ++i;}) );
i = 0;
WScript.Echo( s.replace(/a/g, function(){return ++i;}, 3) );

87,997

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧