我在数组中有一个设置为字符串的字符串
const LANGUAGES = [ "tamil", "hindi", "punjabi", "malayalam", "telugu", "marati", "sinhala" ];
目标 string 在引号(例如“文本”)中将具有不可预测的逗号分隔值的字符串序列
可能的例子是
const text = '["CineIndia","ENG SUBS","IR","SAVER","TAMIL"]'
const text1 = '["SAVER","NFT","CineIndia","ENG SUBS","Hindi","IR","SAVER"]'
我尝试遍历LANGUAGES
并使用indexOf
如何从LANGUAGES
或text
之类的东西中提取text1
中的值
我尝试遍历LANGUAGES
并使用indexOf
。
但这有点说明性,我正在寻找一种更智能的方法来实现相同的目的
答案 0 :(得分:1)
一种实现方法是将.indexOf()
与.toLowerCase()
或.toUpperCase()
结合使用,因为您要搜索的内容与语言列表的情况不同。
const LANGUAGES = ["tamil",
"hindi",
"punjabi",
"malayalam",
"telugu",
"marati",
"sinhala" ];
const text = '["CineIndia","ENG SUBS","IR","SAVER","TAMIL"]';
const text1 = '["SAVER","NFT","CineIndia","ENG SUBS","Hindi","IR","SAVER"]';
LANGUAGES.forEach(function(lang){
if (text.toLowerCase().indexOf(lang)>-1) {
console.log('the constant [text] contains ' + lang);
}
if (text1.toLowerCase().indexOf(lang)>-1) {
console.log('the constant [text1] contains ' + lang);
}
});
答案 1 :(得分:1)
使用JSON.parse
将字符串返回数组:
const text1 = '["SAVER","NFT","CineIndia","ENG SUBS","Hindi","IR","SAVER"]'
console.log(JSON.parse(text1))
现在,您可以使用过滤器了:
const LANGUAGES = [ "tamil", "hindi", "punjabi", "malayalam", "telugu", "marati", "sinhala" ];
const text1 = '["SAVER","NFT","CineIndia","ENG SUBS","Hindi","IR","SAVER"]';
const txtArr = JSON.parse(text1)
const filteredTxt1 = txtArr.filter(x => LANGUAGES.includes(x.toLowerCase()))
console.log(filteredTxt1)
答案 2 :(得分:1)
好吧,所以您正在尝试从定义的语言列表中正确获取文本数组的语言吗?
如果是,这是您的答案:
const LANGUAGES = ["tamil", "hindi", "punjabi",
"malayalam", "telugu", "marati", "sinhala"];
const text = '["CineIndia","ENG SUBS","IR","SAVER","TAMIL"]'
const text1 = '["SAVER","NFT","CineIndia","ENG SUBS","Hindi","IR","SAVER"]'
function getLang(text) {
const array = JSON.parse(text)
let lang = -1
const languages = LANGUAGES.map(x => x.toLowerCase())
for (var i = 0; i < array.length; i++) {
if (languages.indexOf(array[i].toLowerCase()) != -1) {
lang = languages.indexOf(array[i].toLowerCase())
}
}
return LANGUAGES[lang]
}
console.log(getLang(text))
console.log(getLang(text1))