假设我要分割的项目数组(这是针对某个页面)。
我试图“智能地”提取标题,但只提取相关部分。
我也不想要前导/尾随空格。
我不太确定如何做到这一点但是没有在其他循环中放入一堆循环。
function cleanTitle(title) {
// Extract up to first delimiter
var delims = ['|','·','-',':'];
}
我正在使用jquery。
我还将delims数组按照我认为最重要的顺序排列。我没有在移动到下一个数据项之前搜索整个标题的第一个数组项,而是认为它应该一次完成一个字母的整个字符串...它将检查字符串的每个字母是否包含在该数组中。如果没有,它继续前进。我知道很多网址甚至可能包含其中4个中的3个,然后它就不会很好用了。
答案 0 :(得分:1)
您可以使用正则表达式为您完成工作:
var str = "This is a title-And the rest of the string";
var title;
var matchChar = str.match(/^(.*?)[|·\-:]/);
if (matchChar) {
title = matchChar[1]; // "This is a title"
} else {
title = str;
}
答案 1 :(得分:1)
split
接受正则表达式或字符串作为其参数。你可以使解决方案不那么冗长:
function cleanTitle(title) {
return title.split(/[-.|:]/)[0];
}
答案 2 :(得分:0)
所有这些答案 忽略 显而易见且最优雅的解决方案(尽管RegEx肯定是对循环的改进)。只需使用string.split(/^(.*?)[|·\-:]/,1)
这是 ECMAScript 1 ,所以我不明白为什么它不能在所有浏览器中使用。
string.split(separator, limit)
separator Optional. Specifies the character, or the regular
expression, to use for splitting the string. If
omitted, the entire string will be returned (an
array with only one item)
limit Optional. An integer that specifies the number of
splits, items after the split limit will not be
included in the array