Web前端之路让前端飞程序员

JavaScript 替换字符串中的指定子字符串

2017-06-09  本文已影响35人  DreamOver
var replaceAll = function(s, old_str, new_str) {
    var str = s;
    var index = s.indexOf(old_str);
    if (index > 0) {
        var head = s.slice(0, index);
        var tail = s.slice(index + old_str.length);
        str = head + new_str + tail;
    }
    console.log(str);
    return str;
}

// 测试函数
replaceAll("abcdgbcjh0", "bc", "_");  // a_dgbcjh0

这段代码相当于用原生 JavaScript 实现"abcdgbcjh0".replace("bc", "_")

// 查找子字符串在母字符串中的所有位置
var findIndex = function(s1, s2) {
    var len = s2.length;
    var arr = new Array();
    for (var i = 0; i < s1.length; i++) {
        var s = s1.slice(i, i + len);
        if (s === s2) {
            arr.push(i);
        }
    }
    return arr;
}

var replaceLast = function(s, old_str, new_str) {
    var oldList = findIndex(s, old_str);
    var str = s;
    if (oldList.length > 0) {
        var index = oldList[oldList.length - 1];
        var head = str.slice(0, index);
        var tail = str.slice(index + old_str.length);
        str = head + new_str + tail;
    }
    console.log(str);
    return str;
}

replaceLast("abcdgbcjh0", "bc", "_");  // abcdg_jh0
var replaceAll = function(s, old_str, new_str) {
    var all_old = new RegExp(old_str, "g");
    var str = s.replace(all_old, new_str);
    console.log(str);
    return str;
}

// 测试函数
replaceAll("abcdgbcjhbc0", "bc", "_");   // a_dg_jh_0
replaceAll(" ", "bc", "_");  // 返回一个空格
上一篇下一篇

猜你喜欢

热点阅读