0

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?

2

3 Answers 3

2

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)];
Sign up to request clarification or add additional context in comments.

Comments

1

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(" ");

Comments

0

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>" );

Comments

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.