-2

I have a value that I will want to add two hyphens.

For example, if I receive:

FN322KN

I want to transform it to:

FN-322-KN

I am trying to use this solution (Mask javascript variable value) and Im stuck here:

CODE:

var value = 'FN322KN';

var formatted = value.replace(/^(.{2})(.{5}).*/, '$1-$2');

RESULT KO:

'FN-322KN'

Can someone please tell me how I can add the second "-" ?

UPDATE!!

Both Mark Baijens and Buttered_Toast answers are correct. I have one more question though. What if the value comes like FN-322KN or F-N322-KN ? Like, out of format? Because if thats the case, then it adds one hifen where one already exists, making it "--".

Thanks!

  • 2
    Is there any logic to match this string `FN322KN` Like characters A-Z and digits? – The fourth bird Feb 07 '23 at 11:20
  • Do you always want the hyphens after the first 2 characters and after the first 5 characters? – John Williams Feb 07 '23 at 11:21
  • It seems like the OP wants the hyphen whenever a character of `A` to `Z` is followed by a digit ... `/[A-Z](?=\d)/g` ... and whenever a digit is followed by a character of `A` to `Z` ... `/\d(?=[A-Z])/g` ... which leads to either of following solutions ... `'FN322KN'.replace(/[A-Z](?=\d)/g, '$&-').replace(/\d(?=[A-Z])/g, '$&-');` ... `'FN322KN'.replace(/[A-Z](?=\d)|\d(?=[A-Z])/g, '$&-');` – Peter Seliger Feb 07 '23 at 11:46

2 Answers2

-1

Assuming you always want the hyphens after the first 2 characters and after the first 5 characters you can change the regex easily to 3 groups.

var value = 'FN322KN';
var formatted = value.replace(/^(.{2})(.{3})(.{2}).*/, '$1-$2-$3');
console.log(formatted);
Mark Baijens
  • 13,028
  • 11
  • 47
  • 73
-1

Going by the provided content you have, you could try this

(?=(.{5}|.{2})$)

https://regex101.com/r/JZVivU/1

const regex = /(?=(.{5}|.{2})$)/gm;

// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?=(.{5}|.{2})$)', 'gm')

const str = `FN322KN`;
const subst = `-`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);
Buttered_Toast
  • 901
  • 5
  • 13