You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript处理字符串文本中的换行问题?

歌词API获取后按原格式换行展示的正确实现方法

问题描述

调用Musixmatch歌词API获取歌词后,需要在网页上按原歌词格式带换行展示。当前将歌词存储在lyrics变量中,尝试通过在大写字母前添加<br>标签实现换行,但出现了不必要的换行(比如每个"I"前都强制换行)。以下是原代码:

原JS代码

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}'.`;
      }
    })

原HTML代码

<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>

解决方案

Musixmatch API返回的lyrics_body本身已经包含换行符(\n),不需要通过判断大写字母来添加换行。直接将歌词中的换行符替换为HTML的<br>标签即可完美还原原格式。

修改后的JS代码

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);
      const lyrics = data.message.body.lyrics.lyrics_body;

      if (lyrics) {
        // 将歌词中的换行符替换为HTML换行标签
        const formattedLyrics = lyrics.replace(/\n/g, '<br>');
        lyricsContainer.innerHTML = formattedLyrics;
      } else {
        lyricsContainer.textContent = `No lyrics were found for Artist: '${artistValue}', Title: '${titleValue}'.`;
      }
    })
    .catch(error => {
      // 添加上错误处理,避免请求失败时无提示
      lyricsContainer.textContent = `Error fetching lyrics: ${error.message}`;
    });

关键修改点

  1. 移除错误的大写判断逻辑:完全删除遍历字符、判断大写并添加<br>的代码块,这是导致多余换行的根源。
  2. 替换换行符为<br>:使用replace(/\n/g, '<br>')全局替换歌词中的所有换行符,精准还原原歌词的换行格式。
  3. 优化判断条件:将if (data)改为if (lyrics),直接判断是否获取到有效歌词,逻辑更准确。
  4. 添加错误处理:新增.catch()块处理请求失败的情况,提升用户体验。

可选优化:过滤版权提示

Musixmatch返回的歌词末尾通常会带有类似******* This Lyrics is NOT for Commercial use *******的版权提示,如果需要去除,可以在替换换行符后添加:

// 移除版权提示行
const formattedLyrics = lyrics.replace(/\n/g, '<br>').split('<br>*******')[0];

内容的提问来源于stack exchange,提问作者Igor Gryp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 12:05:43