Reputation: 403
I'm trying to create separate lines if a string contains " -"
.
But if it does not contain " -", then leave the string as it is.
So for example,
const string = '-Sentence one -Sentence two -Sentence three'
<div>
{string}
</div>
But this string should be separated into multiple lines if there is a space followed by a hyphen. Then what should be displayed on the website, is a few lines. Instead of one sentence. Also, after replacing, I'd also want to reinsert the "-" as they were.
Upvotes: 1
Views: 79
Reputation: 4332
Consider splitting, mapping, and adding the line break (<br />
) with whatever is missing
Kinda like:
const string = '-Sentence one -Sentence two -Sentence three'
<div>
{string.split(' -').map(x => <span key={somethingUnique}>-{x} <br /></span>)}
</div>
Upvotes: 2
Reputation: 304
You can use split and join to do that.
Here is one liner:
const string = '-Sentence one -Sentence two -Sentence three';
string.split(' -').join('<br>') // if line break in html
string.split(' -').join('\n') // or this
Or you can run loop over the array after split and display them by adding in the required element with new line.
Upvotes: 1
Reputation: 299
you can use .replaceAll on the string, to replace " -"
with "\n"
you'll need to set the white-space
css property of the div to pre-line
Upvotes: 1