There are three ways to replace strings:
-
String connection (simple and easy to think and implement)
Intercept a few of them, and then connect them separately.
var str = "asdf123456"; var sp = function(begain, end, mainStr, replaceStr){ var len = mainStr.length; end = end >= len ? len : end; begain = begain > len || begain < 0 ? 0 : begain; var bStr = mainStr.substr(0, begain); var eStr = mainStr.substr(end, len); return bStr + replaceStr + eStr; } console.log(sp(6, 10, str, "1234")); //asdf121234
-
The string becomes an array and then becomes a string (slightly difficult and not easy to think, but all built-in functions do not need to be implemented by yourself)
Replace the string split into an array, then replace it with slice, and then join to return the string
var str = "asdf123456"; var arr = str.split(''); var replaceArr = arr.splice(6,10, '1234'); var res = arr.join(''); console.log(res);
-
Regular (difficult but minimal code)
var str = "asdf123456"; var res = str.replace(/(\w{6})(\w{4})(.*)/, '$11234$3'); console.log(res);
Summary: For those who are not familiar with regular rules, the second one is recommended. If you want to practice regularity, you can take a look at my notes: Portal