var text = 'cat, bat, sat, fat';
// 在字符串中找到at,并将at替换为ond,只替换一次
var result = text.replace('at', 'ond');
// "cond, bat, sat, fat"
console.log(result);
var text = 'cat, bat, sat, fat'; // 使用/at/g 在全局中匹配at,并用ond进行替换 var result = text.replace(/at/g, 'ond'); // cond, bond, sond, fond console.log(result);
var text = 'cat, bat, sat, fat'; // 使用/(.at)/g 括号为捕获组,此时只有一个,因此所匹配的值存放在$1中 var result = text.replace(/(.at)/g, '$($1)'); // $(cat), $(bat), $(sat), $(fat) console.log(result);
var text = 'cat, bat, sat, fat';
// 使用/at/g 匹配字符串中所有的at,并将其替换为ond,
// 函数的参数分别为:当前匹配的字符,当前匹配字符的位置,原始字符串
var result = text.replace(/at/g, function(match, pos, originalText) {
console.log(match + ' ' + pos);
return 'ond'
});
console.log(result);
// 输出
/*
at 1 dd.html:12:9
at 6 dd.html:12:9
at 11 dd.html:12:9
at 16 dd.html:12:9
cond, bond, sond, fond dd.html:16:5
*/
var text = 'cat, bat, sat, fat';
// 使用/(.at)/g 匹配字符串中所有的at,并将其替换为ond,
// 当正则表达式中存在捕获组时,函数的参数一次为:模式匹配项,第一个捕获组的匹配项,
// 第二个捕获组的匹配项...匹配项在字符串中的位置,原始字符串
var result = text.replace(/.(at)/g, function() {
console.log(arguments[0] + ' ' + arguments[1] + ' ' + arguments[2]);
return 'ond'
});
console.log(result);
// 输出
/*
cat at 1
bat at 6
sat at 11
fat at 16
cond, bond, sond, fond
*/
(function(myFrame) {
myFrame.trim = function(str) {
// ' hello world '
return str.replace(/(^\s*)|(\s*$)/g, '');
};
window.myFrame = myFrame;
})(window.myFrame || {});
// 测试
var str = ' hello world '
console.log(str.length); // 15
console.log(myFrame.trim(str).length); // 11
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有