So I got some code that returns the instructions on how to make a certain dish. For this example I'll use brownies. The value that gets returned is:
1 (21.5 oz) package brownie mix|1 (8 oz.) container sour cream|1 (12 oz.) package semi-sweet chocolate morsels|1 c Chopped pecans
How can I make a new line after | and also remove that character so I got the ingredients in a nice list like this:
- Ingredients 1 (21.5 oz) package brownie mix
- 1 (8 oz.) container sour cream
- 1 (12 oz.) package semi-sweet chocolate morsels
- 1 c Chopped pecans
This is what the code looks like in my program by the way:
{ name: 'Ingredients', value: `${response.data[0].ingredients}`, inline: true }
response.data[0].ingredients is the string of ingredients
CodePudding user response:
If you are using react, you can use the following code
<ul>
{response.data[0].ingredients.split('|').map(item => (
<li>{item}</li>
))}
</ul>
CodePudding user response:
Use replaceAll and template literals to build the html to display the recipe. The snippet shows how you might do this with the data structure you provided.
Snippet
// example raw api data
let response = {
data: [{
ingredients: "1 (21.5 oz) package brownie mix|1 (8 oz.) container sour cream|1 (12 oz.) package semi-sweet chocolate morsels|1 c Chopped pecans"
}]
}
// processed data
let data = [{
name: 'Ingredients',
value: `${response.data[0].ingredients}`,
inline: true
}];
// display item
function show(index) {
recipe.innerHTML = (`
<strong>${data[index].name}</strong>
<ul>
<li>${ data[index].value.replaceAll('|', '</li><li>') }</li>
</ul>
</div>
`);
}
show(0);
body {
font-family: sans-serif;
}
#recipe {
border: 1px solid gray;
border-radius: 0.5rem;
background-color: steelblue;
color: white;
padding: 1rem;
display: inline-block;
}
<div id="recipe"></div>