Home > Back-end >  How to detect escape characters looping through string in javascript?
How to detect escape characters looping through string in javascript?

Time:09-22

I have a scenario where I need to format a string into an array to display it in a different way to the user. So, when I get an escape character (for a new line) \n I need to add that as a separate array item.

Example string : sampe\nanother sample HERE\n\n\nfinal

Should be formatted to ["sample", "another sample", "", "", "final"]

Here the empty strings in the array are for the new lines. How can I achieve this ?

EDIT : I have a special scenario if something in between ${, } that also should be considers as a new array item.

eg : "sampe\n${abc}another sample HERE\n\n\nfinal" in this case, this should be the array ["sample", "${abc}", "another sample", "", "", "final",]

So, this should also be achievable . Currently without considering the escape characters I'm looping through the array to detect ${ and } to do this. So, with the \n how can I get this work

CodePudding user response:

After spend some time on this requirement, I came up with below solution which is a combination of String.split() and String.match() via RegEx :

Live Demo :

// Input string
const str = 'sampe\n${abc}another sample HERE\n\n\nfinal';

// Split the input string based on the character "\n"
const arr = str.split("\n");

// Iterating over an splittted string array to find the match.
arr.forEach((item, index) => {
  const isMatched = item.match(/(\$.*})/)?.length;
  if(isMatched) {
    arr[index] = item.match(/(\$.*})(.*)/)?.slice(1);
  }
});

// Output
console.log(arr.flat());

CodePudding user response:

Just as @JaromandaX commented, you can use string.split("\n") to break your string into an array.
For the ${...} scenario, you can try string.matchAll(/\$\{.*?\}/g) to find these sequences in the string (change .* if you want to restrict the content inside), and then you can split the string using Array.prototype.reduce() like:

// Find and convert all the matches to an array
let matches = Array.from(string.matchAll(/\$\{.*?\}/g));

let result = matches.reduce((res, mat) => {
    res.array.push(string.substring(res.last, mat.index), mat[0]); // each match makes 2 more segments
    res.last = mat.index   mat[0].length; // next segment begins after the match
    return res;
// Use an array to store result and an integer to record where the segment begins
}, {array: [], last: 0});

// Put the remaining segment into result
result.array.push(string.substring(result.last));

// Keep only the segments array as that's the result cared
result = result.array;
  • Related