3

The input:

first line

second line third line

fourth line

The code:

let res = str.split('\n\n')
for (let result of res) {
    res = `<p class="blockquote">${res.replace(/^> /gm, '')}</p>`
}
console.log(`text: ${res}`)

str.split('\n\n') outputs first line,second line third line,fourth line. What I expected.

Now I want to use the for loop to take each item and surround it with p tags. However, I get the following error:

TypeError: undefined is not a function

I'm not very experienced with ES6. Is there something wrong with the loop?

1
  • What are you trying to get in the end? an array of the four strings wrapped in the blockquote tags? can you show the desired output? Commented Oct 19, 2015 at 9:52

2 Answers 2

3

Yes, there's something wrong. Two things.

res = `<p class="blockquote">${res.replace(/^> /gm, '')}</p>`

res is initially an array, so it has no replace method. That's the error you get.

The other thing, once you fix that (replace res with your loop variable result), is that you assign the resulting string to res. I'm not sure what you expect, but I guess it won't work that way.

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

3 Comments

Assigning to res is fine since it's only fetched one time at the start of the loop, though it is a little weird style-wise.
@loganfsmyth I know it doesn't break the loop, but it overwrites each result so that in the end res only contains the last string, not all of them. I can only assume since OP hasn't clarified, but the most obviously desirable outcome would be to map each string to the string with tags.
Ah gotcha, my mistake then.
3

The problem in assigning new value to res variable inside for loop. So after first loop step we will have another value in res and loop will end;

Try this code:

let str = 'first line\n\nsecond line third line\n\nfourth line';
let res = str.split('\n\n')

for (let result of res) {
    let i = `<p class="blockquote">${result.replace(/^> /gm, '')}</p>`
    console.log(i);
}

1 Comment

Assigning to res is fine, though a little weird. It's just the .replace call that is wrong.

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.