1

如果这听起来很傻,我很抱歉,但我是 JavaScript 新手,我想做的是:

假设我有一些带有关键字的文章,例如“培训”。文章会是这样的:

这里有一些文字培训和更多的bla bla bla。我们可以训练这个......使用训练你可以......

现在我想做的是用“ runing ”替换“ training ” ,但我不希望它们全部替换,我只想替换其中一个(随机一个)。

我如何使用 JavaScript 做到这一点?

4

3 回答 3

0

我为这个“问题”写了一个小于 140 字节的函数:https ://gist.github.com/3728254

HTML

<div id="str">Some text here training and more bla bla bla. We can training this... Using training you can...</div>

JS

var replaceR = function(a,b,c,d,e){e=new RegExp(b,"ig");a.innerHTML=a.innerHTML.replace(d?b:e,c)};

    replaceR(document.getElementById('str'), 'training', 'runing', false);

演示

更新

var string = document.getElementById('str').innerHTML,
    newString = string.replace('training', 'running');

document.getElementById('str').innerHTML = newString;

http://fiddle.jshell.net/db3yc/

更新 2

var s = "Some text here training and more bla bla bla. We can training this... Using training you can...",
    nth = 0,
    r = (new Date().getSeconds()) % 4;
s = s.replace(/training/g, function(match, i, original) {
    nth++;
    return (nth === r) ? "running" : match;
});
document.write(s);

http://fiddle.jshell.net/JfYvA/

于 2012-09-26T14:53:32.443 回答
0

我不是 100% 确定,但经过一些小测试后,这应该可以工作:)

function replaceRandom(str, search, replace) {
    var split = str.split(new RegExp("\b?" + search + "\b?")),
        length = split.length - 1,
        rnd = ~~(Math.random() * length),
        result;

    if (length > 0) {
        result = split.map(function(val, idx) {
            return val && (val + (idx === rnd ? replace : search));
        })

        return result.join("").substring(-search.length);
    } else{
        return str;
    }
}

小提琴

于 2012-09-26T15:04:51.597 回答
0

编写了一个函数,该函数在主字符串中构建子字符串位置列表,然后执行单个随机替换:

function replaceRandom(str, needle, replacement)
{
    var indices = [],
    re = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'ig');

    // find all string positions where needle occurs
    while (match = re.exec(str)) {
        indices.push(match.index);
    }

    if (indices.length) {
        // determine a random match to do replacement on
        var pos = indices[Math.floor(indices.length * Math.random())];
        return str.substr(0, pos) + replacement + str.substr(pos + needle.length);
    } else {
        return str;
    }
}

调用它:

var newStr = replaceRandom('Some text here training and more bla bla bla. We can training this... Using training you can...', 'training', 'running');
// newStr now contains a single replacement
于 2012-09-26T15:04:58.400 回答