tctc91
tctc91

Reputation: 1363

Split string where it contains a character into an array item

I have several characters (~) within a sentence. On every ~, I want to split the text before that into an array item. Every array item then needs a <br /> tag at the end.

I tried using replace but it was only working for the first ~ and ignoring the rest. Which is why I think splitting into an array maybe more beneficial down the line.

$("h2").html(function(index, currentHtml) {
    return currentHtml.replaceAll('~', '<br />');
});

Example:

This is some text~This is some text underneath that text~some more text here~and a final bit of text

<strong>This is some text</strong><br />
This is some text underneath that text<br />
some more text here<br />
<strong>and a final bit of text</strong>

Upvotes: 0

Views: 113

Answers (1)

wirey00
wirey00

Reputation: 33661

You can use split with join

$("h2").html(function(index, currentHtml) {
    return currentHtml.split('~').join('<br />');
});

or change it to a regex

$("h2").html(function(index, currentHtml) {
    return currentHtml.replace(/~/g,'<br/>'); // g signifying global
});

Upvotes: 6

Related Questions