0
wordsArray = ['guy', 'like', 'sweet', 'potatoes']; //so on and so forth
string = "I am a **NOUN** and I **VERB** **ADJECTIVE** **NOUN**.";
DELIMITER = "**";

for (var i = 0; i < wordsArray.length; i++)
{
    string.replace(DELIMITER, wordsArray[i]);
}

Hi, this is a simplified version of my code. I'm creating a mad lib, and the length of wordsArray will always be equal to the number of fill in the blanks. The problem with my current code is that in the for loop, it will replace every **. The thing is, I want to replace the entire thing, like **NOUN**, not just **. But since whatever is in between ** ** won't always be the same, string.replace() won't exactly work. Can Anyone suggest me an edit that could replace all the part of speeches but still eventually return string as a, well, block of proper text?

1
  • 1
    You’d do this with a regex. Commented Apr 23, 2018 at 22:01

3 Answers 3

2

You can do it using string.match by catching all those **<STRINGS>** first:

var wordsArray = ['guy', 'like', 'sweet', 'potatoes'];
var string = "I am a **NOUN** and I **VERB-** **ADJECTIVE** **NOUN**.";
var DELIMITER = "**";

var newString = string; // copy the string
var stringArray = string.match(/(\*\*[A-Za-z-]+\*\*)/g); // array of all **<STRINGS>**

for (var i = 0; i < wordsArray.length; i++) {
  newString = newString.replace(stringArray[i], wordsArray[i]);
}

console.log(newString);

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

2 Comments

Oh that's really helpful! One more question though. Sometimes the part of speech may have -, like VERB-ENDING-IN-ING. What would I include in the match parameters to include that -?
@idontknowanygoodusernames do you mean something like **VERB-** ? In that case you will have to update the regex used in .match(). See my updated code above.
0

You can bind your array to the replacer and call replace on your string once, I think it is much simpler:

"I am a **NOUN** and I **VERB** **ADJECTIVE** **NOUN**.".replace(/(\*\*\w+\*\*)/gi,(function(){
    this._currentIndex = this._currentIndex || 0;
    return this[this._currentIndex++];
}).bind(['guy', 'like', 'sweet', 'potatoes']));

//"I am a guy and I like sweet potatoes."

Comments

0

Using reduce:

const string = "I am a **NOUN** and I **VERB** **ADJECTIVE** **NOUN**.";
const newString = ['guy', 'like', 'sweet', 'potatoes'].reduce(
  (theString, replacement) => theString.replace(/\*{2}\w+\*{2}/, replacement),
  string
)

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.