繁体   English   中英

缩短Javascript功能

[英]Shorten Javascript Function

我自己编写了一个函数来将字符串转换为缩写,它目前相当长,并且区分大小写。

我需要一种缩短它的方法,因此它可以100%的时间工作。 目前,如果其中一个分词具有大写字母,如果一个单词以分词结尾,则会搞砸。

我的分词基本上就是我要删除的词(因为大多数公司都不包括它们)。 他们包括:

  • 对于

另外,我删除它们的方式是使用split和join( str.split('and ').join('') )这对我来说似乎不是最简单的方法。

除了这些问题,它工作正常。 任何人都可以帮我缩小功能并解决问题吗? 谢谢。

功能:

String.prototype.toAbbrev = function () {
    var s = [];
    var a = this.split('and ').join('').split('of ').join('').split('the').join('').split('for ').join('').split('to ').join('').split(' ');
    for (var i = 1; i < a.length + 1; i++) {
        s.push(a[i - 1].charAt(0).toUpperCase());
    }

    return s.join('.');
}

经测试公司的产出

The National Aeronautics and Space Administration           ->    N.A.S.A
The National Roads and Motorists' Association               ->    N.R.M.A
Royal Society for the Prevention of Cruelty to Animals      ->    R.S.P.C.A

我认为这样的方法可能会更好:

var toAbbrev = function(str){
    return str.replace(/\b(?:and|of|the|for|to)(?: |$)/gi,''). // remove all occurances of ignored words
               split(' ').                                     // split into words by spaces
               map(function(x){                          
                   return x.charAt(0).toUpperCase();           // change each word into its first letter capitalized
               }).
               join('.');                                      // join with periods
};

这是正则表达式的细分:

/
    \b                    // word boundary
    (?:and|of|the|for|to) // non-capturing group. matches and/of/the/for/to
    (?: |$)               // non-capturing group. matches space or end of string
/gi                       // flags: g = global (match all), i = case-insensitive

这是一个具有不太复杂的正则表达式的替代方法:

var toAbbrev = function(str){
    return str.split(' '). // split into words
               filter(function(x){
                   return !/^(?:and|of|the|for|to)$/i.test(x); // filter out excluded words
               }).
               map(function(x){
                    return x.charAt(0).toUpperCase(); // convert to first letter, captialized
               }).
               join('.'); // join with periods
};

和正则表达式分解:

/
    ^                     // start of string
    (?:and|of|the|for|to) // non-capturing group. matches and/of/the/for/to
    $                     // end of string
/i                        // flags: i = case-insensitive

更短的一个:

str.replace(/(and|of|the|for|to)( |$)/gi, "").replace(/(.).+?(\s|$)/g, "$1.");

为了确保它是大写的,你可以在最后做.toUpperCase

(.)     //selects the first character
.+      //matches the rest of the characters
  ?     //? indicates a lazy match
(\s|$)  //match a space or the end

$1.     //means "the first selected match plus a dot"

让它成为一个正则表达式!

str.replace(/((and|of|the|for|to) )*(.).+?(\s|$)/ig, "$3.");
"Royal Society for the Prevention of Cruelty to Animals"
    .replace(/((and|of|the|for|to) )*(.).+?(\s|$)/ig, "$3.");
//R.S.P.C.A

"Josie and the Pussycats"
    .replace(/((and|of|the|for|to) )*(.).+?(\s|$)/ig, "$3.");
//J.P.

从理论上讲,这应涵盖所有合法的名称。 对于末尾有介词的名字,你可以从技术上做到这一点:

.replace(/((and|of|the|for|to) )*(.).+?(\s|$)((and|of|the|for|to) ?)*/ig, "$3.")

但这显然比有两个replace的更长,这就失去了它的目的。

您也可以使用reduce来完成。 你在做什么本质上是将字符串缩减为缩写 -

str.split(' ').reduce(function(preV, curV, index) {
    if(!/^(and|of|the|for|to)$/.test(curV.toLowerCase())) {
        return preV + curV.toUpperCase().charAt(0) + '.';
    }
    return preV;
}, '');

为什么不尝试这样的事呢?

var a=this.replace(/and |of |the |for |to /gi, '').split(' ');

否则剩下的就好了

只需按以下方式替换字符串:

var a = this.replace(/ and | of | the | for | to /gi, ' ').split(' ');

这也将解决其中一个分裂词在任何主词的末尾的问题。

要删除字符串开头的任何拆分单词,只需执行以下操作:

var pos = a.search(/and |of |the |for |to /i);
if (pos == 0)
   //remove that word

使用ECMA5的可能解决方案

使用Javascript

var toAbbrev = (function (ignore) {
    return function toAbbrev(myString) {
        return myString.split(/[^\w]/).reduce(function (acc, word) {
            if (word && ignore.indexOf(word.toLowerCase()) === -1) {
                acc += word.charAt(0).toUpperCase() + '.';
            }

            return acc;
        }, '');
    };
}(['and', 'of', 'the', 'for', 'to']));

console.log(toAbbrev('The Silica & Sand Society'));
console.log(toAbbrev('The National Aeronautics and Space Administration'));
console.log(toAbbrev('The National Roads and Motorists\' Association'));
console.log(toAbbrev('Royal Society for the Prevention of Cruelty to Animals'));

产量

S.S.S.
N.A.S.A.
N.R.M.A.
R.S.P.C.A. 

jsFiddle上

您可以改进split正则表达式( /[^\\w]/ )以处理更多奇怪的事情。 或者只是拆分空格/\\s/并添加到排除列表中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM