代码之家  ›  专栏  ›  技术社区  ›  Rataiczak24

正在从字符串的一部分删除文本

  •  2
  • Rataiczak24  · 技术社区  · 7 年前

    我需要删除不同字符串中的文本。

    我需要一个函数,将使以下。。。

    test: example1
    preview: sample2
    sneakpeak: model3
    view: case4
    

    ...如下所示:

    example1
    sample2
    model3
    case4
    

    我试过使用 substr substring 但未能找到解决方案。

    我用过 selected.substr(0, selected.indexOf(':')) 但我看到的只是冒号前的文字。 selected

    由于字符串的长度不同,因此也不能硬编码。有什么建议吗?

    4 回复  |  直到 7 年前
        1
  •  2
  •   Dinesh undefined    7 年前

    使用 split 作用split将返回一个数组。要删除空格,请使用trim()

    var res = "test: example1".split(':')[1].trim();
    
    console.log(res);
        2
  •  2
  •   ibrahim mahrir    7 年前

    substring 采用两个参数:切割开始和切割结束(可选)。

    substr 采用两个参数:切割起点和切割长度(可选)。

    substr 从开始索引剪切到结束):

    var result = selected.substr(selected.indexOf(':'));
    

    你可能想要 trim

    var result = selected.substr(selected.indexOf(':')).trim();
    
        3
  •  0
  •   Steven Scaffidi    7 年前

    试试这个:

    function getNewStr(str, delimeter = ':') {
    
    
      return str.substr( str.indexOf(delimeter) + 1).trim();
    
    
    }
        4
  •  0
  •   Nebojsa Nebojsa    7 年前

    你可以用正则表达式 /[a-z]*:\s/gim

    var string = "test: example1\n\
    preview: sample2\n\
    sneakpeak: model3\n\
    view: case4";
    
    var replace = string.replace(/[a-z]*:\s/gim, "");
    
    console.log(replace);

    example1
    sample2
    model3
    case4