How can I add two hyphens in an RegEx expression? - javascript

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!

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);

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);

Related

in Javascript, what is the best practice to convert stringified date to 'YYYY.MM.DD' format?

For example, I get string '20201101'
What I do is convert the string to '2020.11.01'
Here is what I did.
const dateString = '20201101'
const dateArr = dateString.split('')
dateArr.splice(4, 0, '.')
dateArr.splice(7, 0, '.')
const dateFormat = dateArr.join('')
I think it is bit long, so I'm looking for another answer for this.
Thank you!
You can also use a RegExp with replacement patterns in a String#replace() call.
const dateStr = '20201101';
const result = dateStr.replace(/(\d{4})(\d{2})(\d{2})/, '$1.$2.$3');
console.log(result)
You could use template literals.
`${dateString.slice(0, 4)}.${dateString.slice(4, 6)}.${dateString.slice(6, 8)}`
Not a very clean way to do it, but it is only one line.
Your code is fine, and readable. But if you're looking for an alternative maybe look at regular expressions.
const str = '20201101';
// Group four digits, then two digits,
// and then two digits
const re = /(\d{4})(\d{2})(\d{2})/;
// `match` returns an array of groups, the first element of
// which will be the initial string, so first remove that,
// and then `join` up the remaining elements using
// a `.` delimiter
const out = str.match(re).slice(1).join('.');
console.log(out);
Additional documentation
match

Using regex to remove characters till the last -

I'm new to regex and trying to figure out how to remove characters till the last - in the string. I currently have strings in the format like this:
purple-hoodie.jpg-1625739747918
I am trying to remove characters to essentially be left with:
-1625739747918
Does anyone have any advice on how to approach this? I'm struggling to work out how to indicate to reach the last - in the string, if that is even possible?
Thanks
Just use lastIndexOf
let str = 'purple-hoodie.jpg-1625739747918'
console.log(str.substring(str.lastIndexOf('-')))
I prefer a match approach here:
var input = "purple-hoodie.jpg-1625739747918";
var output = input.match(/-\d+$/)[0];
console.log("match is: " + output);
But this assumes that the input would end in all digits. A more general regex approach might use a replace all:
var input = "purple-hoodie.jpg-1625739747918";
var output = input.replace(/^.*(?=-)/, "");
console.log("match is: " + output);
Here is my solution.
const txt = 'purple-hoodie.jpg-1625739747918';
const result = txt.replace(/-\d+$/, '');
console.log(result)
This removes the last trailing digits prefixed by -.

Need to extract part of a url using Regex [duplicate]

This question already has answers here:
Template literal inside of the RegEx
(2 answers)
Closed 2 years ago.
I would like to extract a substring from an s3 URL using Regex rather than with string manipulation functions.
My requirement is to retrieve dynamodbtablename/05abd315-2e0b-4717-919d-1cc6576ebe19 out of a URL s3://s3bucket/dynamodbtablename/05abd315-2e0b-4717-919d-1cc6576ebe19
However, I have not been able to arrange the regex expression to give me what I want.
I would like the regex to parse in this form but I know that I am missing something in the regex line.
const url = 's3://s3bucket/dynamodbtablename/05abd315-2e0b-4717-919d-1cc6576ebe19';
const patternMatches = url.match(new RegExp(s3://${s3bucket}/${dynamodbtablename}/([a-f\d-]+)));
const migrationDataFileS3Key = patternMatches[indexOfResultingArrayWithDesiredSubstring]
I was able to come up with the expression below to retrieve the UUID/GUID and have had to concatenate it with ${s3bucket} to form the S3 bucket key. However, I am not happy with this solution. I require the above.
const url = 's3://s3bucket/dynamodbtablename/05abd315-2e0b-4717-919d-1cc6576ebe19';
const patternMatches = url.match(/([a-f\d-]+)/g);
const migrationDataFileS3Key = massiveTableItem + '/' + patternMatches[patternMatches.length - 1];
Thank you very much for your help.
You may not need a regular expression: split the URL on / and take the element you need from that. Like:
{
console.log(`s3://s3bucket/dynamodbtablename/05abd315-2e0b-4717-919d-1cc6576ebe19`
.split(`/`) // split on forward slash
.slice(-2) // take the last 2 elements from the resulting array
.join(`/`) // extract it
);
// alternatively
console.log(`s3://s3bucket/dynamodbtablename/05abd315-2e0b-4717-919d-1cc6576ebe19`
.match(/([\w\-])+/g)
.slice(-2)
.join(`/`)
);
// or (use capture groups)
const {groups: {root, hashpath}} =
/(?<root>s3:\/\/s3bucket\/)(?<hashpath>[\w\-\/]+)/
.exec(`s3://s3bucket/dynamodbtablename/05abd315-2e0b-4717-919d-1cc6576ebe19`);
console.log(hashpath);
// or (just substring from known index)
const url = `s3://s3bucket/dynamodbtablename/05abd315-2e0b-4717-919d-1cc6576ebe19`;
console.log(url.substr(url.indexOf(`/`, 5) + 1))
}
you can use capture groups, like
var str = "s3://s3bucket/dynamodbtablename/05abd315-2e0b-4717-919d-1cc6576ebe19";
var myRegexp = /s3:\/\/s3bucket\/(.*)/;
var match = myRegexp.exec(str);
console.log(match[1]);
// returns 'dynamodbtablename/05abd315-2e0b-4717-919d-1cc6576ebe19'
I was able to eventually arrive at a solution that was closest to the format that I wanted as required in my question. I was able to do it by combining the solution of #sudhir-bastakoti and #wiktor-stribiżew as each individual answer did not address my question completely.
I am grateful to everyone that answered my question including #kooiinc. I checked out his last answer options and it worked. However, I wanted the answer in a certain format.
const s3bucket = 's3bucket';
const url = 's3://s3bucket/dynamodbtablename/05abd315-2e0b-4717-919d-1cc6576ebe19';
const migrationDataFileS3Key = url.match(new RegExp(String.raw`s3://${s3bucket}/(.*)`))[1];

Regex - Match a string between second occurance of characters

I have a string of text that looks something like this:
?q=search&something=that&this=example/
In that example, I need to grab that . I'm using the following regex below:
var re = new RegExp("\&(.*?)\&");
Which going re[1] is giving me:
something=that - but it needs to be only that
I tried:
var re = new RegExp("\=(.*?)\&");
But that gives me everything from the first equals sign, so:
search&something=that
Is the output when it just needs to be:
that
I need to somehow target the second occurrences of 2 characters and grab whats in between them. How best do I go about this?
You can use
/something=([^&]+)/
and take the first group, see the JavaScript example:
let url = '?q=search&something=that&this=example/';
let regex = /something=([^&]+)/
let match = regex.exec(url);
console.log(match[1]);
split seems more suited to your case:
"?q=search&something=that&this=example/".split("&")[1].split("=")[1]
Then you could also implement a simple method to extract any wanted value :
function getValue(query, index) {
const obj = query.split("&")[index];
if(obj) obj.split("=")[1]
}
getValue("?q=search&something=that&this=example/", 1);

How to remove timestamp using regex from a date string in javascript

New to regex.
Need regular expression to match strings like T17:44:24Z from parent strings like 2015-12-22T17:44:24Z using javascript regex.
Once match is found will replace it with null or empty space.
To be specific i am trying to remove the time stamp from date string and obtain only date part.
Please help me in this
You can use a simple regex like this:
T\d{2}:\d{2}:\d{2}Z
or
T(?:\d{2}:){2}\d{2}Z
Working demo
In case your T and Z are dynamic the, you can use:
[A-Z]\d{2}:\d{2}:\d{2}[A-Z]
Code
var re = /T\d{2}:\d{2}:\d{2}Z/g;
var str = '2015-12-22T17:44:24Z';
var subst = '';
var result = str.replace(re, subst);
You don't need regex on this. You just split the string by T and get the second element from array, which would be 17:44:24Z in your case.
var date = '2015-12-22T17:44:24Z';
var result = date.split('T')[1];
If you also want to preserve T, you can just prepend it to the result:
var result = 'T' + date.split('T')[1]

Categories