Javascript中可跨浏览器使用的新行计数器

Cross-browser ready new line counter in Javascript

本文关键字:新行 计数器 浏览器 Javascript      更新时间:2023-09-26

我有两个问题:

  • 我的功能看起来像

    function count() { var value = ids.val(); return (value == '') ? 0 : value.replace(/'s,?|,$/g, '').split(/'r'n|'r|'n/).length; }

我想做的是跳过空白并计算所有新行例如:

85
96
75
<whitespace>
76

count()必须返回4而不是5。如何修改我的函数?

  • 如何将换行分隔的单词/数字转换为逗号分隔的内容

例如:

85
96
75<whitespace>
<whitespace>
76

我想修剪所有的空白,并将整个内容转换为类似85,96,75,76的内容。我该怎么做?

最简单的方法是.filter($.trim).map($.trim),它首先删除所有空白条目,然后通过删除周围的空格来清除其余条目:http://jsfiddle.net/BtLzf/1/.

var vals = ids.val()
             .split(/'r'n|'r|'n/)
             .filter($.trim)
             .map($.trim);
vals.length; // 4
vals.join(); // 85,96,75,76

.filter/.map是ES5,这意味着您需要一个用于旧浏览器的填充程序。

我认为你需要做一个循环来检查每一行的长度,因为在这种情况下,你得到的是行尾字符的数量,即使这一行是空的,也是5。。。得到这个迭代器,你还可以得到逗号列表

我建议使用正则表达式模式,这样可以更好地清理问题。也许:

^(''d+)''s?$

$(function(){
    var matches = $('#txtInput').text().match(/^('d+)'s?$/mg);
    $('#txtResult').text(matches.join(','));
});​

工作示例:http://jsfiddle.net/mZ97L/

这样的东西怎么样?

// Count of items in the list.
function count(){
    var list = delimitedList();
    return list.split(",").length;
}
// Get list separated by comma.
function delimitedList(){
    var value = ids.val();
    return value.replace(/'s+/g, ",");
}

http://jsfiddle.net/wT23h/2/