0

Question:

Is it possible to keep the selected delimiter using javascript [.split], without involving regex? In below example I am sending in the commands using 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.

The output:

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;

Wanted behaviour:

I need the output to include the delimitor [ } ]. The result lines should look line this:

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

I did find below question but it does not use javascript split, it uses regex:

Javascript split include delimiters

Toolbox
  • 2,333
  • 12
  • 26
  • If it is ECMAScript 2018 compliant, use `s.split(/(?<=})(?!$)/)` – Wiktor Stribiżew Jan 25 '19 at 19:09
  • Or, `s.match(/[^}]*(?:}|$)/g).filter(Boolean)` – Wiktor Stribiżew Jan 25 '19 at 19:12
  • 1
    To answer your question: No, you cannot do this with `split` without using a RegExp. Is there a reason you want to avoid RegExp? FWIW this seems like an [XY problem](https://meta.stackexchange.com/a/66378/140350). If you're trying to parse or format a string of CSS in some way, you should ask for help with that problem. – Jordan Running Jan 25 '19 at 19:14
  • @Wiktor. I guess thats the closest I come to an answer. -To clarify, I wanted to understand if it was possible by using [.split] to tell the system that it should include the mentioned delimiter in the result response. I take it that it is not possible. If so, I have to accept that I need to use a regex within the [.split] to get the proper result. – Toolbox Jan 25 '19 at 19:14
  • @Jordan. Reason to wait with regex, was that I am fairly new at regex and meanwhile learning regex I wanted in parallel to find existing solution to solve my question. I am attempting to breakdown CSS code into pieces to learn methods and regex for splits – Toolbox Jan 25 '19 at 19:24

1 Answers1

0

Here's a way using replace - although technically there is a regex involved. Techical in an almost pedantic way since it matches the actual strings, only between slashes rather than quotes.

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

var partsOfString = text_string.replace(/;}/g, "};\n")
 
console.log(partsOfString);
 
stever
  • 1,232
  • 3
  • 13
  • 21