【问题标题】:Strip text after comma to the end of line去除逗号后的文本到行尾
【发布时间】:2016-08-09 13:10:05
【问题描述】:

我需要删除逗号后的所有文本到行尾。比如我有这样一段文字:

一、二、三\n 橙色、白色、蓝色

我需要得到这样的东西:

一个\n 橙色

【问题讨论】:

  • 太好了……你试过什么?
  • 我不擅长正则表达式,所以这是解决它的一种方法,我认为它不是一个好方法。 var a = "one, two, three\n orange, white, blue"; var p = []; a.split("\n").forEach(function(item){ p.push(item.split(",")[0]); }); p.join("\n");

标签: javascript regex string text


【解决方案1】:

你可以使用一个非常简单的正则表达式:

replace(/,.*/g, '')

var s = "one, two, three\n orange, white, blue";
console.log(s.replace(/,.*/g, ''));

详情

  • , - 匹配 , 然后...
  • .* - 0+ 个字符而不是换行符
  • /g - 多次

并替换为空字符串。

【讨论】:

    【解决方案2】:
    const string = "one, two, three\n orange, white, blue";
    const commaArray = string.split(',');
    const lineBreakArray = commaArray[2].split('\n');
    const myString = commaArray[0] + "\n" + lineBreakArray[1]; // one\n orange
    

    【讨论】:

    • @WiktorStribiżew 你可以把它作为答案
    猜你喜欢
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 2010-12-13
    • 2021-01-25
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多