我正在尝试创建单独的行if a string contains " -"
。但是如果它不包含“-",那么就让字符串保持原样。举个例子,
const string = '-Sentence one -Sentence two -Sentence three'
<div>
{string}
</div>
但是,如果后面有空格和连字符,则应将此字符串分隔为多行。然后在网站上应该显示的是几行。而不是一句话。此外,在替换后,我还希望重新插入"-“。
发布于 2021-04-18 02:58:40
可以对字符串使用.replaceAll,将" -"
替换为"\n"
您需要将white-space
的div css属性设置为pre-line
发布于 2021-04-18 03:13:05
考虑拆分、映射和添加包含缺失内容的换行符(<br />
有点像:
const string = '-Sentence one -Sentence two -Sentence three'
<div>
{string.split(' -').map(x => <span key={somethingUnique}>-{x} <br /></span>)}
</div>
发布于 2021-04-18 02:59:58
您可以使用split和join来完成此操作。
这里有一行代码:
const string = '-Sentence one -Sentence two -Sentence three';
string.split(' -').join('<br>') // if line break in html
string.split(' -').join('\n') // or this
或者,您可以在拆分后在数组上运行循环,并通过添加所需的元素和新行来显示它们。
https://stackoverflow.com/questions/67144767
复制