0

假设我有一组要拆分的项目(这是一个页面)。

我正在尝试“智能”提取标题,但仅提取相关部分。

我也不想要前导/尾随空格。

不过,我不太确定如何去做这件事.. 没有在其他循环中放置一堆循环。

function cleanTitle(title) {
    // Extract up to first delimiter
    var delims = ['|','·','-',':'];
} 

我正在使用 jquery。

我还将 delims 数组按照我认为最重要的顺序排列。而不是在移动到下一个之前搜索第一个数组项的整个标题,我认为它应该一次一个字母地处理整个字符串......它会检查字符串的每个字母是否包含在该数组中。如果没有,它会继续前进。我知道很多 url 可能包含所有 4 个中的 3 个,否则它就不会很好地工作。

4

3 回答 3

1

You can use a regex to do the work for you:

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

Working demo: http://jsfiddle.net/jfriend00/kxVMB/

于 2012-09-19T23:32:13.757 回答
1

split接受正则表达式或字符串作为其参数。您可以使解决方案不那么冗长:

function cleanTitle(title) {
    return title.split(/[-.|:]/)[0];
}

演示:http: //jsfiddle.net/AlienWebguy/JkRv6/

于 2012-09-19T23:38:16.953 回答
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

于 2017-06-06T20:12:51.703 回答