Home > Enterprise >  Javascript Regex convert string
Javascript Regex convert string

Time:05-16

I am not familiar with Javascript Regex. Can anyone tell me how to convert strings like "Minus162Plus140" into "-162,140", or "Plus162Minus140" into "162,-140" by using match or replace? thanks so much in advance!

CodePudding user response:

Building on the previous answer, you'll also need to handle other cases, like "Plus162Minus140":

text = "Minus162Plus140";
text = text.replace(/^Minus/, "-");   // Handle when Minus comes first
text = text.replace("Minus", ",-");   // And second
text = text.replace(/^Plus/, "");     // Handle when Plus comes first
text = text.replace(/Plus/, ",");     // And second

But this approach itself is brittle, and assumes that the string will always be of the form /^(Minus|Plus)\d (Minus|Plus)\d $/, which you could validate first with a regular expression:

if (/^(Minus|Plus)\d (Minus|Plus)\d $/) {
  ... do the replacement
} else {
  ... handle the error
}

CodePudding user response:

You can just use string replace:

text = "Minus162Plus140";
text = text.replace("Minus", ",-");
text = text.replace("Plus", ", ");

console.log(text);

Or regex:

text = "Minus162Plus140";
re = /Plus/;
text = text.replace(re, ', ');
re = /Minus/;
text = text.replace(re, ',-');

// Then to remove the initial comma:

re = /^,/;
text = text.replace(re, '');

console.log(text);

CodePudding user response:

Details commented in example below

const str = `Minus162Plus140 Plus162Minus140
Plus58 Minus899`;

const result = [...str.matchAll(/Minus\d |\d /g)]
//[["Minus162"],["140"],["162"],["Minus140"],["58"],["Minus899"]]
.flatMap(n => 
//will flatten all of the arrays
 (n[0]
//target each sub-array convert to number
.replace('Minus', '-')));
//replace 'Minus' with '-'
console.log(JSON.stringify(result))

  • Related