Gago Design
Gago Design

Reputation: 992

Select & replace a random word in javascript

I'd like to write a code in javascript that selects a random word from a text, and replaces it for another word.

Here's my code:

var text = "dog cat apple stone";
var keyword = text[Math.floor(Math.random()*text.length)]; // select random word
var new_phrase = text.replace( keyword, "house"); // replace for other word

document.write("<p>" + text + "</p>" );
document.write("<p>" + new_phrase + "</p>");

However, this replaces a letter in the text not a word. Like this: "dog chouset apple stone"

How can I select a random word not a letter?

Upvotes: 0

Views: 2050

Answers (3)

Johan &#214;brink
Johan &#214;brink

Reputation: 143

Using an array

http://www.w3schools.com/jsref/jsref_obj_array.asp

you can store the values and then refer back to them with an index and get the value back.

var text=["dog","cat","apple", "stone"];

var keyword = Math.floor((Math.random()*text.length)); 
text[keyword] = "house"; // replace for other word

document.write("<p>" + text + "</p>" );

Upvotes: 0

user160820
user160820

Reputation: 15210

Accoring to Kepp it Simple principle i would say

var text = "dog cat apple stone";
arrText = text.split(" ");

it will give you and array of words back. After replacing any word in array you can again use

arrText.join(" ");

Upvotes: 1

KooiInc
KooiInc

Reputation: 122906

Using text[someIndex] you are selecting one character from text. Try splitting the string and use the resulting array:

var text = "dog cat apple stone"
   ,txttmp = text.split(/\s+/)
   ,keyword = txttmp[Math.floor(Math.random()*txttmp.length)];

Upvotes: 2

Related Questions