用Javascript动态格式化带有项目符号的项目列表



用例

API返回一个类似The ingredients are * apple* carrot *potato的字符串。请注意,项目符号点之间的间距通常不会一致。

在我填充一个长字符串的元素中,我只会得到一个简短的标题和一个列表。因此,我希望列表(字符串的部分将以*开头(首先用<ul>包装,然后让每个项目都用<li>包装。


样本字符串

This is a list of sodas * Dr. Pepper *LaCroix * 7up  *sprite * Fanta * Coke Zero *Pepsi

应执行的步骤

  1. * Dr. Pepper *LaCroix * 7up *sprite * Fanta * Coke Zero *Pepsi包裹在<ul>
  2. 将单个项目包装在<li>
  3. 抓住项目符号*和它与任何字符之间的间距并将其删除

所需的innerHTML输出

This is a list of sodas
<ul>
<li>Dr. Pepper</li> 
<li>LaCroix</li>
<li>7up</li>  
<li>sprite</li> 
<li>Fanta</li> 
<li>Coke Zero</li> 
<li>Pepsi</li>
</ul>

演示

CodePen 上的当前演示

根据您的应用程序逻辑,您需要使用v-for来填充配方的项目,并将您的输入字符串转换为带有数组的对象以传递给呈现器:

function getRecipe (str) {
var items = str.split('*').map(s => s.trim())
return { title: items.shift(), items }
}
// in your Vue
Vue.use(VueMarkdown)
...
recipe: getRecipe(taco.recipe)
...
<p>
{{ taco.recipe.title }}
<ul>
<li v-for="item of taco.recipe.items">
{{ item }}
</li>
</ul>
</p>

您还应该将初始状态设置为空值,这样Vue就不会在初始化期间抛出错误:

data {
taco: {
name: '',
condiment_name: '',
condiment_recipe_url: '',
recipe: { title: '', items: [] }
}
}

也可以使用vue-markdown来渲染markdown语法。

您可以使用正则表达式拆分字符串,然后生成所需的html

const s = 'This is a list of sodas * Dr. Pepper *LaCroix * 7up  *sprite * Fanta * Coke Zero *Pepsi';
let chunks = s.split(/ ?* ?/);
const heading = chunks[0];
chunks = chunks.slice(1);
let output = `${heading}
<ul>
${chunks.map(c => `<li>${c}</li>`).join('n')}
</ul>
`;
console.log(output);

var str = "This is a list of sodas * Dr. Pepper *LaCroix * 7up  *sprite * Fanta * Coke Zero *Pepsi";
//split string into an array using * as delimiter
var items = str.split('*');
//grab the first item since it's the title, not a soda
var title = items.shift();
//create an html string var
var html = `${title}<ul>`
//loop over remaining array elements and append to our html
items.forEach((el) => {
html += `<li>${el.trim()}</li>`;
});
html += '</ul>';
//display as HTML
document.getElementById('target').innerHTML = html;
<div id="target"></div>

最新更新