简体   繁体   English

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

[英]if JavaScript string starts with hyphen then count occurrences

Basically I have an array of strings like this: 基本上我有一个这样的字符串数组:

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

I'm trying to loop each string and check if the string starts with a hyphen, if so count how many times and then remove. 我正在尝试循环每个字符串,并检查字符串是否以连字符开头,如果是这样,则数数,然后删除。

I can do it kind of like this: 我可以这样做:

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

I haven't tested but you can get the idea.. 我还没有测试过,但您可以理解。

I'm hoping for an easier solution maybe with a regex? 我希望也许有一个正则表达式更简单的解决方案? Any help? 有什么帮助吗?

Thanks. 谢谢。

-- EDIT -- -编辑-

I need to count and remove the hyphens from each string because I have a text area for a user to enter a string with new lines and hyphens. 我需要计算和删除每个字符串中的连字符,因为我有一个文本区域供用户输入带有新行和连字符的字符串。

Textarea value: 文字值:

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

I am then exploding the textarea value into an array: 然后,我将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
};

Assuming you're already looping through to get 'string' (I've used 'val' below to remove possible confusion with 'string' type in other languages) 假设您已经遍历以获得“字符串”(我在下面使用“ val”来消除其他语言中“字符串”类型的可能混淆)

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

Edit: tested and there's no need to escape the '-' in this usage 编辑:经过测试,在这种用法中无需转义“-”

Explanation: 说明:

  • .replace is a method of all strings .replace是所有字符串的方法
  • using // allows a regex 使用//允许使用正则表达式
  • ^ start of line ^行首
  • '-' literal '-'文字
  • '+' one or more “ +”一个或多个

Update: to include get the count, you can do: 更新:要获取计数,您可以执行以下操作:

var matches = val.match("^(-+).*");
length = matches == null ? 0 : matches[1].length;
  • match is a method of all strings match是所有字符串的方法
  • '^' match start “ ^”比赛开始
  • '(' ')' applies a group, which is returned in the second value of matches, ie the [1] '('')'应用了一个组,该组在matchs的第二个值中返回,即[1]
  • ?: used because if there's no match, then matches will be null ?:之所以使用,是因为如果没有匹配项,则匹配项将为null

Update to match question's edit: 更新以匹配问题的编辑:

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(/^-+/, '')
};
var count = [];
array = array.map(function(str) {
    var match = str.match(/^(-*) ?/);
    count.push(match[1].length);
    return str.substr(match[0].length);
});

You can count matches (ie how many hyphens) with a regular expression , and then replace them using the same RegEx matches. 您可以使用正则表达式计算匹配项(即,多少个连字符),然后使用相同的RegEx匹配项替换它们。

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

You can simply map over the strings, using a regular expression to match (and implicitly count) the hyphens and attaching the remainder of each string. 您可以简单地在字符串上进行映射,使用正则表达式来匹配(并隐式计算)连字符,并附加每个字符串的其余部分。

 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> 

Yet another variant with map and replace with function 具有map功能替换的另一个变体

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

 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); 
 <pre id='res'></pre> 

Here is how you can get count and replacement in single match invocation : 这是在单个匹配调用中如何获得计数和替换的方法:

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

If an element doesn't have - at start then above code will get count=0 and replaced same as original string. 如果一个元素没有-在开始时,那么上面的代码将得到count=0replaced为原始字符串。

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

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