0

how would i randomly replace a string in a text using javascript or jquery?

given: <p>foo bar foo baz foo</p>

I want to just randomly replace 1 occurrence of 'foo' with 'buz', so possible results would be:

<p>buz bar foo baz foo</p>
<p>foo bar buz baz foo</p>
<p>foo bar foo baz buz</p>

1 Answer 1

3
var $element = $('p');
var string = 'foo';
var count = $element.text().match(string, 'g').length;

if(count) {
    var rand = Math.floor((Math.random() * count) + 1);
    $element.text(function(i, text) {
        var matchNumber = 0;
        return text.replace(new RegExp(string, 'g'), function(text) {
            matchNumber++;
            if(matchNumber == rand) {
                return 'buz';
            }
            return text;
        });
    });
}

Explanation:
First of all we have to know the range to the random. We can get it matching the string and then get the length.

Then you have to match it again and increase a counter which will be used to know which match is the currently one.

If the current match is equal to the random number we have to replace the text.

demo

Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly...except I have one rub -- I want to do the replacement 1 or 2 times at random. So BUZ would show up once or twice in the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.