Home > Mobile >  How to create regex with replace spaces and add spaces between semicolons
How to create regex with replace spaces and add spaces between semicolons

Time:07-08

how to create a regex that replaces a space with an underscore and adds spaces between semicolons?

Replacing a space with a underscore in the entire text can be solved:

data.replace(/ /g, "_");

But how to solve the situation with semicolons at the same time? The point is that I have a text file that separates individual texts with an underscore. If it does not contain any data, it simply continues in the next semicolons:

data;data;;data;;;data

I need it to add a blank space between the semicolons in each case. The problem is that the number of semicolons is irregular and I always need to add a space:

data;data; ;data; ; ;data

There are more than 10,000 such lines in the text file. Is there a solution for my case?

const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you";

const replaceData = data.replace(/ /g, "_");

/*
//
//This is not a solution for me, as the number of semicolons is not always the same. And I also can't combine this regex into one.
//
//const replaceData2 = data.replace(/;;/g, "; ;");
*/

console.log(replaceData);

The result should be like this:

red; ;I_WW2;123; ; ;error;more; ;blue; ; ; ;123;I_love_you

Thanks

CodePudding user response:

You can call .replace twice:

const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you";
var repl = data.replace(/  /g, "_").replace(/;(?=;)/g, "$& ");

console.log(repl);

But make sure to replace spaces with _ before inserting spaces between ;s.

  • .replace(/ /g, "_"): Replace 1 spaces with _
  • .replace(/;(?=;)/g, "$& "): Insert space between 2 adjacent semicolons

CodePudding user response:

this will help you to get your desire output.

  1. Positive Lookbehind (?<=;)
  2. Positive Lookahead (?=;)

and we replace it with " " space.

const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you";
const replaceData = data.replace(/(?<=;)(?=;)/g, " ");
console.log(replaceData)

CodePudding user response:

If you want to do it with one regex, it can be done with a callback argument, but this will also cost execution time. Like I wrote in comments, it may turn out to be better to stick with 2 replace calls. Just see how it performs in your environment, and on your data.

Here is how it would work with callback:

const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you";

const result = data.replace(/ |(?<=;)(?=;)/g, m => " _"[m.length]);

console.log(result);

The regex has a zero-length match between two semi-colons, so when it matches that, m will be the empty string (in the callback). So the size of m can be used to distinguish the two cases, and length can then serve to select the replacement character (either a space or an underscore).

  • Related