你能帮我把JavaScript代码简化成几行吗?
我有一个JavaScript代码,可以获取当前通过API播放的歌曲的歌词 有时(并非总是)歌词会在开头返回标题,这正是我想要删除的 有时开头的标题是大写的,有时是大写和小写的 例如:你能帮我把JavaScript代码简化成几行吗?,javascript,Javascript,我有一个JavaScript代码,可以获取当前通过API播放的歌曲的歌词 有时(并非总是)歌词会在开头返回标题,这正是我想要删除的 有时开头的标题是大写的,有时是大写和小写的 例如: SWEET CHILD O' MINE She's got a smile that it seems to me Reminds me of childhood memories Where everything was as fresh as the bright blue sky Now and th
SWEET CHILD O' MINE
She's got a smile that it seems to me
Reminds me of childhood memories
Where everything was as fresh as the bright blue sky
Now and then when I see her face
She takes me away to that special place
And if I stare too long, I'd probably break down and cry
........
我创建了一个有点麻烦的代码,成功地从一开始就删除了标题
我想看看他们是否能帮助我在更少的行中简化代码
我将分享代码中我们感兴趣的部分,以便于帮助,如果你想要所有的代码,我没有问题分享它
currentSong
包含正在播放的歌曲的标题
lyric
包含通过API获得的完整歌词
this.refreshLyric = function(currentSong, currentArtist) {
//another code that does not interest
//...
//...
//lyric variable contains the complete lyrics of a song obtained through an API
var lyric = data.mus[0].text;
//divide the string CurrentSong (contains the song title) into parts
let splitCurrenSong = currentSong.split(' ');
//I get the length of the array
let largeCurrentSong = splitCurrenSong.length;
//divide the string lyric into parts
let splitLyric = lyric.split(' ');
//I get the first elements of the lyric array with the length limit of largeCurrentSong
let pieceLyric = splitLyric.slice(0, largeCurrentSong);
//I get all elements of the splitCurrenSong array
let pieceSong = splitCurrenSong.slice(0, largeCurrentSong);
//join arrays
let joinLyric = pieceLyric.join(' ');
let joinSong = pieceSong.join(' ');
//I check if the chunk of the joinLyric string matches the same chunk of joinSong
if (joinLyric.toLocaleLowerCase() == joinSong.toLocaleLowerCase()) {
//remove the matching items
splitLyric.splice(0, largeCurrentSong);
//put the resulting join array into a variable
lyrics = splitLyric.join(' ');
//remove the spaces from the beginning and end of lyrics
lyric = lyrics.trim()
}
//another code that does not interest
//...
//...
}
编辑:回复@iamaword
如API返回的屏幕截图所示:
文本:
包含完整歌曲的歌词
名称:
歌曲标题
用这句话我完全可以知道这首歌的名字:
var nameSong=data.mus[0]。名称
但是我不认为这是必要的,因为我从currentSong
变量中获取歌曲的名称,这是在get
命令中发送的获取歌词的变量
最终编辑:归功于@cerbiralfart
完整代码:
this.refreshLyric = function(currentSong, currentArtist) {
var proxy_URL = PROXYURL;
var vagalume_api = 'https://api.vagalume.com.br/search.php?';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status === 200) {
var data = JSON.parse(this.responseText);
if (data.type === 'exact' || data.type === 'aprox') {
var lyric = normalizeText(data);
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
var openLyric = document.getElementsByClassName('lyrics')[0];
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
var powered = "Vagalume"
var URL_lyric = 'https://www.vagalume.com.br';
//Powered by image src...
const parent = document.querySelector('.chartlyrics');
parent.innerHTML = '';
var img = document.createElement("img");
img.src = "img/103-fundo-escuro.jpg"
img.setAttribute('class', "")
parent.appendChild(img);
parent.appendChild(document.createElement('br'));
parent.append('Powered by ');
// Powered by link a href...
document.getElementById('powered_by').innerHTML = ''
var a = document.getElementById('powered_by')
.appendChild(document.createElement("a"));
a.href = URL_lyric;
a.target = "_blank";
a.rel = "noopener noreferrer";
a.textContent = powered;
} else {
var page = new Page();
page.refreshLyric2(currentSong, currentArtist);
}
} else {
var page = new Page();
page.refreshLyric2(currentSong, currentArtist);
}
}
}
xhttp.open('GET', proxy_URL + vagalume_api + API_KEY + '&art=' + currentArtist + '&mus=' + currentSong.toLowerCase(), true);
xhttp.send()
}
function normalizeText(response){
// First unpack the data, get the right name and text values
let {mus:[{name, text}]} = response;
// Now get the part of the text that might be the title
let titleLength = name.length;
let maybeTitle = text.substring(0, titleLength);
// Compare the two titles and trim if they match
if (name.toLowerCase() === maybeTitle.toLowerCase() && exceptions.includes(maybeTitle.toLowerCase()) == false){
text = text.substring(titleLength)
}
//Remove any leading or trailing whitespace and return
return text.trim();
}
//song names excepted from being removed in lowercase ['one song', 'two song', etc..]
const exceptions = ['sweet emotion'];
我在normalizeText
函数中添加了一个新条件,以检查要删除的歌曲名称是否不在异常范围内
// Compare the two titles and trim if they match
if (name.toLowerCase() === maybeTitle.toLowerCase() && exceptions.includes(maybeTitle.toLowerCase()) == false){
我创建了一个常量exceptions
,其中必须手动添加小写歌曲名称,并用逗号分隔
//song names excepted from being removed in lowercase ['one song', 'two song', etc..]
const exceptions = ['sweet emotion'];
有几种方法可以清理代码,主要是如何解包数据以及如何比较两个字符串
function normalizeText(response){
// First unpack the data, get the right name and text values
let {mus:[{name, text}]} = response;
// Now get the part of the text that might be the title
let titleLength = name.length;
let maybeTitle = text.substring(0, titleLength);
// Compare the two titles and trim if they match
if (name.toLowerCase() === maybeTitle.toLowerCase()){
text = text.substring(titleLength)
}
//Remove any leading or trailing whitespace and return
return text.trim();
}
编辑:sintax error toLowerCase added()歌词是否带有换行符,您可以通过类似正则表达式的歌词进行拆分。拆分(/\r?\n/)是的,歌词带有\nalso*您可以通过从中获取歌词的相同api获取标题吗?因为如果可以的话,你可以对第一段歌词做一些检查,看看它们是否与标题匹配,标题也可以通过相同的API获得。我在newline上拆分,然后知道第一个数组将是标题(或不是)。这至少可以将其缩小到确定特定字符串是否为标题的路径。我已编辑以共享完整的代码,因为我不知道如何在我的代码中实现该函数。所有此函数都以
data
作为参数,而不是行var lyric=data.mus[0]。text代码>通过结束我提议的代码
:使用const-lyric=normalizeText(数据)
我修复了中的一个小错误。toLowerCase
缺少括号,现在它可以工作了。抱歉@Cerberalfart,我敢编辑你的答案,但是我需要社区信任成员的批准才能完成编辑。我非常感谢你的正确回答
function normalizeText(response){
// First unpack the data, get the right name and text values
let {mus:[{name, text}]} = response;
// Now get the part of the text that might be the title
let titleLength = name.length;
let maybeTitle = text.substring(0, titleLength);
// Compare the two titles and trim if they match
if (name.toLowerCase() === maybeTitle.toLowerCase()){
text = text.substring(titleLength)
}
//Remove any leading or trailing whitespace and return
return text.trim();
}