如果JavaScript字符串以连字符开头,则计算出现次数

时间:2015-06-02 13:56:01

标签: javascript arrays regex

基本上我有一个像这样的字符串数组:

var array = [
    'Top level',
    '- Sub item',
    '-- Child of sub',
    'Another top',
    'Yet another top',
    '- Child',
];

我试图循环每个字符串并检查字符串是否以连字符开头,如果是,则计算多少次然后删除。

我可以这样做:

if (string.substring(0, 1) == "-") {
    // ...
} else if (string.substring(0, 2) == "--") {
    // ...
} else if (string.substring(0, 3) == "---") {
    // ...
}

我没有经过测试,但你可以得到这个想法..

我希望通过正则表达式提供更简单的解决方案?有什么帮助吗?

感谢。

- 编辑 -

我需要计算并删除每个字符串中的连字符,因为我有一个文本区域供用户输入带有新行和连字符的字符串。

Textarea值:

Top level
- Sub item
-- Child of sub
Another top
Yet another top
- Child

然后我将textarea值爆炸成数组:

var array = textareaValue.split('\n');

for (var i = 0; i < array.length; i++) {
    var this = array[i];
    // Now check for hyphens and count how many
    // if (hyphens === '-')
    // else if (hyphens === '--') ...etc
};

6 个答案:

答案 0 :(得分:2)

假设你已经循环获取'string'(我在下面使用'val'来消除与其他语言中'string'类型的混淆)

val = val.replace(/^-+/, '')

编辑:经过测试,无需在此用法中转义' - '

说明:

  • .replace是所有字符串的方法
  • 使用//允许正则表达式
  • ^行首
  • ' - 'literal
  • '+'一个或多个

更新:要包括获取计数,您可以这样做:

var matches = val.match("^(-+).*");
length = matches == null ? 0 : matches[1].length;
  • match是所有字符串的方法
  • '^'匹配开始
  • '('')'应用一个组,在第二个匹配值中返回,即[1]
  • ?:使用因为如果没有匹配,那么匹配将为null

更新以匹配问题的编辑:

var array = textareaValue.split('\n');

for (var i = 0; i < array.length; i++) {
    var thisValue = array[i];
    // Now check for hyphens and count how many
    var matches = thisValue.match("^(-+).*");
    var hyphenCount = matches == null ? 0 : matches[1].length;
    var fixedValue = thisValue.replace(/^-+/, '')
};

答案 1 :(得分:0)

resolve: {
   simpleStringParam: ["$q", "$timeout", function($q, $timeout){
      var deferred = $q.defer();
          $timeout(function(){
              deferred.resolve("Allo!");
          },8000);
      return deferred.promise;
   }]
}

答案 2 :(得分:0)

您可以使用正则表达式计算匹配(即多少个连字符),然后使用相同的RegEx匹配替换它们。

有关正则表达式和JavaScript的更多信息:http://www.w3schools.com/js/js_regexp.asp

答案 3 :(得分:0)

您可以简单地映射字符串,使用正则表达式匹配(并隐式计数)连字符并附加每个字符串的其余部分。

var array = [
  'Top level',
  '- Sub item',
  '-- Child of sub',
  'Another top',
  'Yet another top',
  '- Child',
];

function countCharacter(data, char) {
  var rex = /^(-*)(.*)$/; // hyphens in first group, body in second
  return data.map(function(it) {
    var res = it.match(rex);
    console.log(res);
    return {
      count: res[1].length,
      text: res[2]
    };
  });
}

document.getElementById('r').textContent = JSON.stringify(countCharacter(array, '-'));
<pre id=r></pre>

答案 4 :(得分:0)

mapreplace with function

的另一种变体
array.map(function(v){
    var s,vv=0;
    s = v.replace(/^-+/,function(p1){
     vv = p1.length;
     return '';
}) 
    return {
        s:s, v:vv
    }
});

&#13;
&#13;
var array = [
    'Top level',
    '- Sub item',
    '-- Child of sub',
    'Another top',
    'Yet another top',
    '- Child',
];    
var mapped = array.map(function(v){
        var s,vv=0;
        s = v.replace(/^-+/,function(p1){
         vv = p1.length;
         return '';
    }) 
        return {
            name:s, count:vv
        }
    });
  
  document.getElementById('res').innerHTML = JSON.stringify(mapped, null,2);
&#13;
<pre id='res'></pre>
&#13;
&#13;
&#13;

答案 5 :(得分:0)

以下是单一匹配调用中计数和替换的方法:

select x , y,(x/cast(y as float)*100) from 
 (select count(distinct t1.ST_NUM) as x
    from table2 t2, 
           table1 t1,
             table t3
where 
  t2.CD in ($CD1)
  and t2.ITM_CD=($ITM_CD)
  and t2.div=($div)
  and t2.div= t1.div
   and t2.scn_cd = t1._scn_cd
   and t1.week_end =t3.week_end 
   and t3.week_end between ($startdate_1)  and  ($enddate_1))a1
   cross join 
   (select count(distinct t1.ST_NUM) as y
         from from table2 t2, 
                   table1 t1,
                   table t3
where 
  t2.CD in ($CD1)
  and t2.ITM_CD=($ITM_CD)
  and t2.div=($div)
  and t2.div= t1.div
   and t2.scn_cd = t1._scn_cd
   and t1.week_end =t3.week_end 
   and t3.week_end between ($startdate_2)  and  ($enddate_2))a2

如果元素在开始时没有for (var i = 0; i < array.length; i++) { var elem = array[i]; var m = (elem.match(/^(-+)(.*)$/) || ['', elem]); var count = m[1].length; var replaced = m[2]; }; ,那么上面的代码将-count=0与原始字符串相同。

相关问题