0

I can't seem to get my head around javascript regex, so I need your help!

I need to transform the following:

1234567891230

Into:

urn:epc:id:sgln:12345678.9123.0

I already did it with a normal javascript algorithm (see underneath), but we need to be able to configure this transformation. I just need it for the default configuration value!

Using slice it would be:

var result = "urn:epc:id:sgln:" + myString.slice(0, 8) + "." + 
myString.slice(8, 12) + "." + myString.slice(12);

If you can include an explanation in your answer I would be grateful :)

10
  • 4
    What have you tried? And what does "I already did it with a normal javascript algorithm, but we need to be able to configure this transformation." mean? Commented Apr 19, 2018 at 14:16
  • 1
    What's the logic? Like why a dot after 8 and 3? Why the extra 0? Commented Apr 19, 2018 at 14:19
  • What is wrong with what you have done so far? Commented Apr 19, 2018 at 14:48
  • rmlan: I included the "javascript" algorithm in the question. I am not very familiar with regex, so I have basically tried to stitch pieces together from similar problems. Commented Apr 19, 2018 at 14:49
  • rmlan: We want to store the regex in a database, so that we can transform the number in various ways and not have it hard coded. Our current problem is that a customers test environment doesn't use the same "urn:epc:id:sgln:" prefix. Commented Apr 19, 2018 at 14:52

2 Answers 2

3

If you want to use regex for this try the following:

var regex = /(\d{8})(\d{4})/;
var splittedNumber = regex.exec("123456789123");
var result = "urn:epc:id:sgln:"+splittedNumber[1]+"."+splittedNumber[2]+".0";
console.log(result);

But I would recommend the string split you did already.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use a regex to capture 3 groups for 12345678, 9123 and 0 and use a word boundary \b at the begin and at the end.

Then using slice you could get all elements but leave out the first element from the array returned by match because that contains the full match that we don't need.

After that you could join the elements from the array using the dot as the separator.

\b(\d{8})(\d{4})(\d)\b

let str = "1234567891230";
let prefix = "urn:epc:id:sgln:";
console.log(prefix + str.match(/\b(\d{8})(\d{4})(\d)\b/).slice(1).join("."));

1 Comment

Thanks for this. I think we will go ahead and use your solution. It means we will have two configuration values; one for the prefix (string) and one for inserting dots at the right places (regex).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.