【问题标题】:Javascript include delimiter when using command [.split]Javascript 在使用命令 [.split] 时包含分隔符
【发布时间】:2019-06-19 15:38:36
【问题描述】:

问题:

是否可以使用 javascript [.split] 保留选定的分隔符,而不涉及正则表达式?在下面的示例中,我使用 node.js 发送命令。

// A css text string.
var text_string = "div-1{color:red;}div-2{color:blue;}";

// Split by [}], removes the delimiter:
var partsOfStr = text_string.split('}');

// Printouts
console.log("Original: " + text_string); // Original.
console.log(partsOfStr);                 // Split into array.
console.log(partsOfStr[0]);              // First split.
console.log(partsOfStr[1]);              // Second split.

输出:

Original: div-1{color:red;}div-2{color:blue;}
[ 'div-1{color:red;', 'div-2{color:blue;', '' ]
div-1{color:red;
div-2{color:blue;

想要的行为:

我需要输出包含分隔符 [ } ]。结果行应如下所示:

div-1{color:red};
div-2{color:blue};

我确实找到了以下问题,但它不使用 javascript 拆分,它使用正则表达式:

Javascript split include delimiters

【问题讨论】:

  • 如果它符合 ECMAScript 2018,请使用 s.split(/(?<=})(?!$)/)
  • 或者,s.match(/[^}]*(?:}|$)/g).filter(Boolean)
  • 回答您的问题:不,如果不使用 RegExp,您将无法使用 split 执行此操作。您是否有理由避免使用 RegExp? FWIW 这似乎是XY problem。如果您尝试以某种方式解析或格式化 CSS 字符串,您应该寻求有关该问题的帮助。
  • @Wiktor。我想那是我最接近答案的地方。 -为了澄清,我想了解是否可以通过使用 [.split] 告诉系统它应该在结果响应中包含提到的分隔符。我认为这是不可能的。如果是这样,我必须接受我需要在 [.split] 中使用正则表达式才能获得正确的结果。
  • @乔丹。等待正则表达式的原因是,我在正则表达式方面相当新,同时我想同时学习正则表达式,以找到现有的解决方案来解决我的问题。我正在尝试将 CSS 代码分解成片段以学习拆分的方法和正则表达式

标签: javascript node.js regex string split


【解决方案1】:

这是一种使用replace 的方法——尽管从技术上讲涉及到一个正则表达式。几乎是迂腐的技术,因为它匹配实际的字符串,只在斜杠而不是引号之间。

var text_string = "div-1{color:red;}div-2{color:blue;}";

var partsOfString = text_string.replace(/;}/g, "};\n")
 
console.log(partsOfString);
 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    相关资源
    最近更新 更多