【问题标题】:How do I split a particular string value?如何拆分特定的字符串值?
【发布时间】:2018-09-20 01:57:40
【问题描述】:

我有两种类型的字符串,比如...

var a = "23 years 08months 12 days";
var b = "5 years 8 months 1 days";

我想减少这个字符串...

"23 years 08 months" 
"5 years 8 months"

我尝试像这样使用替换和拆分...

var a = "23 years 03 months 24 days";
var b = a.replace(/ /g,'')
var c;
if(b.length < 23){c = b.slice(0,13) }

但这不是固定的方法!请问有什么建议吗?

【问题讨论】:

  • @Sahish 最好的选择是使用momentjs.com
  • 我认为 Moment.js 是用于格式化日期,而不是拆分字符串

标签: javascript string replace slice


【解决方案1】:

这是一个工作示例,根据您的评论,您表示要在几个月内切断:

var a = "23 years 08 months 12 days";
var b = "5 years 8 months 1 days";

console.log(a.split("months")[0]+" months");
console.log(b.split("months")[0]+"months");

【讨论】:

    【解决方案2】:

    这应该可以解决问题,而不使用正则表达式

    var s = 'months';
    var a = '23 years 03 months 24 days';
    
    a = a.substring(0, a.lastIndexOf(s) + s.length);
    

    【讨论】:

      【解决方案3】:

      您可以搜索和替换年份和月份值。

      function yearMonth(s) {
          return s.replace(/^(\d+)\s*years\s*(\d+)\s*months(.*)/, '$1 years $2 months');
      }
      
      console.log(yearMonth("23 years 08months 12 days"));
      console.log(yearMonth("5 years 8 months 1 days"));

      【讨论】:

        【解决方案4】:

        只需在 months 上拆分并将字符串 months 附加到拆分数组的第一个值:

        var a = "23 years 08 months 12 days";
        var b = "5 years 8 months 1 days";
        var res = a.split('months')[0] + 'months';
        console.log(res);
        res = b.split('months')[0] + 'months';
        console.log(res);

        也可以使用子串方式:

        var a = "23 years 08 months 12 days";
        var b = "5 years 8 months 1 days";
        
        var res = a.substring(0, a.indexOf('months')) + 'months';
        console.log(res);
        
        var res = b.substring(0, b.indexOf('months')) + 'months';
        console.log(res);

        【讨论】:

          【解决方案5】:

          你可以试试下面的正则表达式:

          (?<=months).*
          

          (?

          这会导致 JS:

          a.replace(/(?<=months).*/g,'');
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-01-04
            • 1970-01-01
            • 1970-01-01
            • 2015-12-18
            • 2021-06-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多