I'm working with an API with song lyrics and print the fetched lyrics on the web page but I want them to print with line breaks like this:
Hello, it's me
I was wondering if after all these years you'd like to meet
To go over everything
They say that time's supposed to heal ya, but I ain't done much
healingHello, can you hear me?
I'm in California dreaming about who we used to be
When we were younger and free
I've forgotten how it felt before the world fell at our feetThere's such a difference between us
And a million milesHello from the other side
How can I accomplish this when I get lyrics as a string. Say the lyrics are stored in a variable for example let lyrics
I tried creating line breaks before each capital letter but then I get line breaks where I don't want them. For example, in front of each "I".
Here is my attempt to solve the task but it turns out the wrong way, not the way the original lyrics are written.
searchForm.addEventListener('submit', function (event) {
event.preventDefault();
const artistValue = artistInput.value;
const titleValue = titleInput.value;
fetch(
`https://api.musixmatch.com/ws/1.1/matcher.lyrics.get?q_track=${titleValue}&q_artist=${artistValue}&apikey=${apiKey}`
)
.then((response) => response.json())
.then((data) => {
console.log(data);
console.log(data.message.body.lyrics.lyrics_body);
let lyrics = data.message.body.lyrics.lyrics_body;
if (data) {
let characters = lyrics.split('');
for (var i = 0; i < characters.length; i++) {
// Check if the character is uppercase
if (
characters[i] === characters[i].toUpperCase() &&
characters[i] !== characters[i].toLowerCase()
) {
// Add a line break before the uppercase character
characters[i] = '<br>' + characters[i];
}
}
let modifiedLyrics = characters.join('');
lyricsContainer.innerHTML = modifiedLyrics;
} else {
lyricsContainer.textContent = `No lyrics were found for Artist: '${artistValue}', Title: '${titleValue}'.`;
}
})
<form id="lyrics-search-form">
<input id="artist" type="text" placeholder="Artist..." />
<input id="title" type="text" placeholder="Title..." />
<button id="search-btn" disabled>Search</button>
</form>
<div class="lyrics-div">
<p id="lyrics"></p>
</div>