Search⌘ K
AI Features

Solution: Turning a List of Phrases Into an Array of Strings

Explore how to turn a list of phrases into an array of strings by applying JavaScript regular expressions. Understand how to handle whitespace and use the match method to extract each phrase as an individual array item, enabling dynamic text processing with regex.

We'll cover the following...

Solution #1

Alright, ready on your side?

The first solution we could think of is the following:

C++
const fs = require("fs")
function regExparser(txt) {
let arrContent = txt.replace(/(.+)/g, '"$1",')
let myCode = `let myArray = [${arrContent}]`
return myCode
}
fs.readFile("./sample.txt", "utf8", (err, content) => {
if(err) console.error(err)
console.log(content.toString())
console.log(regExparser(content.toString()))
})

Assuming a text file with the exact same content as the one shown on the diagram above, here is the output that we get: ...

Notice how ...