Reputation: 21
I would like to replace a string with a random string from an array if that string equals a certain condition.
So far I have this (which doesn't address the condition part).
the html:
<div>
<span class ="test">foo</span>
</div>
<div>
<span class ="test">bar</span>
</div>
<div>
<span class ="test">test</span>
</div>
<div>
<span class ="test">random</span>
</div>
the code:
$(".test").each(function () {
var quotes = new Array("foo", "bar", "baz", "chuck"),
randno = quotes[Math.floor(Math.random() * quotes.length)];
$('.test').text(randno);
});
This sets every ".test" class the same thing. I get:
foo
foo
foo
foo
or
bar
bar
bar
bar
How do I make this only replace the string if it equals say "foo"?
If I have multiple "foos" How do i get each "foo" it replaces to be random not all set to the same thing?
Upvotes: 2
Views: 1006
Reputation: 9634
Another approach is to shuffle the replacements array, than use it:
/* Famous shuffle function */
Array.prototype.shuffle = function() {
for (var j, x, i = this.length; i; j = Math.floor(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
return this;
};
$.fn.extend({
randomReplace: function(text, replacements) {
replacements.shuffle();
return this.each(function () {
if( $(this).text().toLowerCase()==text.toLowerCase() )
$(this).text(replacements.pop());
});
}
});
$('.test').randomReplace('foo', ['one', 'two', 'three', 'four', 'five', 'six']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="test">foo</span>
<span class="test">bar</span>
<span class="test">foo</span>
<span class="test">foo</span>
<span class="test">bar</span>
Upvotes: 1
Reputation: 133403
You need to use this
in the .each()
callback method
$(".test").each(function() {
var quotes = new Array("foo", "bar", "baz", "chuck"),
randno = quotes[Math.floor(Math.random() * quotes.length)];
//Check condition
if ($(this).text() === "foo") {
$(this).text(randno);
}
});
Alternatively you can also use .text(function)
var quotes = new Array("foo", "bar", "baz", "chuck");
$(".test").text(function(_, text) {
var randno = quotes[Math.floor(Math.random() * quotes.length)];
//Check condition
if (text === "foo") {
return randno;
}
return text;
});
$(function() {
var quotes = new Array("foo", "bar", "baz", "chuck");
$(".test").text(function(_, text) {
var randno = quotes[Math.floor(Math.random() * quotes.length)];
//Check condition
if (text === "foo") {
return randno;
}
return text;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span class="test">foo</span>
</div>
<div>
<span class="test">bar</span>
</div>
<div>
<span class="test">test</span>
</div>
<div>
<span class="test">random</span>
</div>
Upvotes: 2