abcabcabcabcabcabc
变为
北京bc北京bc北京bc北京bc北京bc北京bc

方法一:

split和join

function f3(str,m,n){
var arr = str.split(m) // ["", "bc", "bc", "bc", "bc", "bc", "bc"]
var str2 = arr.join(n) //北京bc北京bc北京bc北京bc北京bc北京bc
return str2
}
var str = 'abcabcabcabcabcabc';
m = 'a'
n = '北京'
res = f3(str,m,n)
console.log(res)

方法二:

数组

function f4(str,m,n){

var arr = str.split('')
for(var i=0;i<=arr.length-1;i++){
if(arr[i]===m){
arr[i] = n
}
}
var res = arr.join('')
return res
}
var str = 'abcabcabcabcabcabc';
m = 'a'
n = '北京'
res = f4(str,m,n)
console.log(res)

方法三:

while indexOf replace

function f5(str,m,n){
while(str.indexOf(m)!=-1){
str = str.replace(m,n)
}
return str
}
var str = 'abcabcabcabcabcabc';
m = 'a'
n = '北京'
res = f5(str,m,n)
console.log(res)

注: replace默认执行的是懒惰模式 只会替换第一个符合的字符

var str = 'abcabcabcabcabcabc';
var res = str.replace('a' , '北京');
console.log( str ); //abcabcabcabcabcabc
console.log( res ); //北京bcabcabcabcabcabc