Outline
js the replace () first argument can be a string, can also be a regular, when a string, can only replace one, not the overall situation, how to achieve that effect replaceAll it?
At the time of the interview, there was a problem Shredded Code, entitled: find the first string in the second string, third string and then replaced, and can not use any api, you can not use regular expressions, only with simple basic grammar . In fact, it is to let you write a native replaceAll (), and write some of their api
// 这是我的写法,面试官仍有点不满的感觉,他说用两个for循环,一个个去检测,其实下面的做法也是类似的复杂度
// 有同学有关于js版本更好的做法,请在下方留言,大家一起学习学习
function subString (str, i, j) {
let result = ''
for (i; i < j; i++) {
result += str[i]
}
return result
}
function replaceAll(str, before, after) {
if (before.length > str.length) {
return str
}
let searchLength = before.length
let result = ''
for (let i = 0; i < str.length; i++) {
// 匹配到第一个字符
if (str[i] === before[0]) {
// 看before长度是否长于剩下的长度
if (i > str.length - before.length) {
break
// 足够长
} else {
let compareStr = subString(str, i, i + searchLength)
if (compareStr === before) {
let front = subString(str, 0, i)
let end = subString(str, i + searchLength, str.length - 1)
str = front + after + end
}
}
}
}
return str
}