计算不包括关键字列表的字符串长度?

时间:2012-01-16 20:00:57

标签: javascript jquery

我根据输入字符串的长度验证了多个字段。但是,以下数组中的任何值都不得计入字符串长度:

var omittedSubStrings = ["%KEYWORD%","{Keyword:AltText}","%CITY_STATE%","%CITY%","%KEYWORD%","%KEY_WORD%","%QUERY_KEYWORD%","%QUERY_KEY_WORD%","$CLICK_ID$","$LOCATION$","%URLENC_CITY%","%NOSPACE_CITY%","%STATE%","$USER_PLACEMENT_INV_ID$"];

所以例如我的字符串是:

var str = "Hello %CITY%";

我想得到该字符串的长度s.t它等于6.多个变量可以在一个字符串中使用,并且它们必须全部不计入长度。

建议?

2 个答案:

答案 0 :(得分:5)

function countSubstringless(str, subStrings) {
    var length = subStrings.length;
    for (var i=0; i<length; i+=1) {
        str = str.replace(subStrings[i], '');
    }
    return str.length;
}

var omittedSubStrings = ["%KEYWORD%","{Keyword:AltText}","%CITY_STATE%","%CITY%","%KEYWORD%","%KEY_WORD%","%QUERY_KEYWORD%","%QUERY_KEY_WORD%","$CLICK_ID$","$LOCATION$","%URLENC_CITY%","%NOSPACE_CITY%","%STATE%","$USER_PLACEMENT_INV_ID$"];
var str = "Hello %CITY%";

console.log(countSubstringless(str, omittedSubStrings));
// 6

答案 1 :(得分:2)

这是一个替代答案。

请注意,这假设单词列表中没有特殊的正则表达式字符(或者它们被正确保护):

var omittedSubStrings = ["%KEYWORD%","{Keyword:AltText}","%CITY_STATE%","%CITY%","%KEYWORD%","%KEY_WORD%","%QUERY_KEYWORD%","%QUERY_KEY_WORD%","$CLICK_ID$","$LOCATION$","%URLENC_CITY%","%NOSPACE_CITY%","%STATE%","$USER_PLACEMENT_INV_ID$"]

// make regular expression alternation for all words, global search
var re = new RegExp(omittedSubStrings.join("|"), "g")

var str = "%KEYWORD%Hello %CITY%"
str.replace(re, "").length // 6

(“这样更好吗?”这个问题留给读者练习。)

快乐的编码。