字符串匹配angularjs / javascript最多2个字符

时间:2015-11-17 16:22:10

标签: javascript angularjs regex

我有一个匹配空格后所有字母的功能。我的意思是;

"this is my string" --> tims

这样做:

$scope.getLetters = function(str) {
            var matches = str.match(/\b(\w)/g);
            var acronym = matches.join('');
            return acronym;
        }

其中str当然是我从html传递的字符串。它工作得很好,但我会提取最多2个字符。所以如果字符串是

"this is my string" 

我只会ti而不是其他人。我该怎么办?

1 个答案:

答案 0 :(得分:1)

slice之前使用join

var str = "this is my string";
str.match(/\b\w/g).slice(0,2).join('')
//=> "ti"