Changing a string from user input - javascript

Having some troubles figuring this one out as I'm not too sure what you'd even call it.
I'm trying to take a users input and swap it around, so for example:
1 input for the date: DD MM YYYY, I want them to input it as such and then change it to YYYYDDMM server side before sending it where it needs to go.
I've tried looking at regex expressions and str replace but it doesn't appear to have an option to pull the end of a users string and place it in a different location. Any insight would be appreciated of where I could find some more help on this or what direction to go in.

You can do it with regex if you capture each part of the date string in a group, and then echo the groups back in a different order, without the spaces:
const reformatDate = dateStr => dateStr.replace(/^(\d{2}) (\d{2}) (\d{4})$/, '$3$1$2');
console.log(reformatDate('05 12 2000'));
console.log(reformatDate('10 31 2010'));
console.log(reformatDate('01 01 2018'));
With Javascript's .replace, $ followed by a number in the second parameter passed to the .replace function replaces the $# with that captured group in the regular expression. For example, $3 gets replaced with whatever was matched by the third (...).
The same sort of replacement syntax works in PHP:
function reformatDate($dateStr) {
return preg_replace('/^(\d{2}) (\d{2}) (\d{4})$/', '$3$1$2', $dateStr);
}

Related

Regex for last occurence of String between fix determinator

So I am having a specific string returned in the following structure:
"http://www.google.com/search","XYZ","Some other Value","false","false","2017-12-13"
I only want to find the last occurrence of a date from the format "YYYY-MM-dd", as it could also be, that the values "false" may be returning a date.
I am not experienced in regular expressions, but the last thing I achieved was to receive 2017-12-12"* with the following expression :
**((?:[^"]"*){10})$**
Looking for the occurrence of a date in the desired format won't help, as multiple dates might occur.
This is why I want to check for the last String between quotation marks. How will I get this date without quotation marks?
I want to check for the last String between quotation marks
Just:
regexp_replace(myvalue, '^.*"([^"]+)"$', '\1')
Regexp breakdown:
^ beginning of the string
.* any sequence of 0 to N characters
" double quote
( beginning of the capturing group
[^"]+ as many characters as possible other than a double quote (at least one)
) end of the capturing group
" double quote
$ end of string
The regexp matches on the entire string and replaces it with the catpured part.
Demo on DB Fiddle:
with t as (select '"http://www.google.com/search","XYZ","Some other Value","false","false","2017-12-13"' myvalue from dual)
select regexp_replace(myvalue, '^.*"([^"]+)"$', '\1') mydate from t
| MYDATE |
| :--------- |
| 2017-12-13 |
If needed, you can be more specific by specifying the expected date format in the capturing group:
regexp_replace(myvalue, '^.*"(\d{4}-\d{2}-\d{2})"$', '\1')
You could use the following regex to do it:
/^(?:".*?",)*"(.*?)"$/
Alternatively, you could use String#split() and String#slice():
const output=input
.split(',')
.pop()
.slice(1,-1)
Use simple regexp_substr as following:
select regexp_substr('"http://www.google.com/search","XYZ","Some other Value","false","false","2017-12-13"',
'((\d){4}(-)(\d){2}(-)(\d){2})"$',1,1,null,1)
from dual;
db<>fiddle demo
Here, parameters of the regexp_substr are as follows:
REGEXP_SUBSTR( string, pattern [, start_position [, nth_appearance [, match_parameter [, sub_expression ] ] ] ] )
Cheers!!
If I understand correctly, "false", "false", "2017-12-13" can be any combination of three dates or three falses, or anywhere in between, and you're looking to find the last date. I would use
(\d{4}-\d\d-\d\d(?!.*\d{4}-\d\d-\d\d))
Which will capture a date as long as it is not followed by another.
See my example here:
https://regex101.com/r/GAkpDI/1/
"http://www.google.com/search","XYZ","Some other Value","2018-04-09","false","<<2017-12-13>>"
"http://www.google.com/search","XYZ","Some other Value","<<2018-12-09>>","false","false"
"http://www.google.com/search","XYZ","Some other Value","false","<<2000-09-17>>","false"
"http://www.google.com/search","XYZ","Some other Value","2018-12-09","2000-09-17","<<2017-12-13>>"
I have put the matches inside of <<>>.
Edit: If you don't know the format the date will be in, then you could swap it for something that just finds numbers, dashes, and slashes:
https://regex101.com/r/GAkpDI/2/
([\d-\/]+(?!.*[\d-\/]+))
This will be more likely to fail, as it will find anything [0123456789-/], but if your program will only ever put a date or false in there, it should still be viable.

Is it possible to reuse the logic defined in regex expression twice

Is it possible to reuse the logic defined in regex expression twice like
I want to match if Day range is defined like
mon-wed or monday-friday.
Here's regex expression used to match one day expression
/\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\b/
It works fine for mon, tuesday etc
but I want to reuse it to with - in the middle
I guess you don't want to just copy and paste the part you want repeated to form something like this:
\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)-((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\b
You can store them as strings, then you concatenate the strings and finally, pass them into new RegEx(...):
var partToBeRepeated = "\\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\\b"
var regex = new RegEx(partToBeRepeated + "-" + partToBeRepeated)
I think this should work
\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\b-\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\b
You can check here for more

Remove space in a date string

I'm getting a date from a database that sometimes has spaces in the times (there isn't a way to clean up DB as I don't have control). I need to remove the spaces so I can format it to a Javascrpt date.
For example:
5 : 03 PM
As you can see, this is incorrect. I've looked at Moment.js and Regex to remove spaces around the colon, but not sure how that's done or if that's the proper way. Is there a way to remove this space?
Thanks all!
Only to delete the space around the colon, try the following; (where $1 refers to the first capture group, that is the only one (:))
a.replace(/\s*(:)\s*/, "$1");
or if you wish to simplify it further, without any capturing group;
a.replace(/\s*:\s*/, ":");
If you want to, you can actually parse that date string with Moment.js, you just need to include the spaces in your formatting string:
var time = moment('5 : 03 PM', 'h : m A');
Then you can format it however you want:
time.format('h:mmA'); // "5:30PM"
time.format('hh:mm A'); // "05:03 PM"
time.format('HH:mm'); // "17:03"
For completeness you could aviod regexp:
'5 : 03pm'.split(':')
.map(function(part) { return part.trim(); })
.join(':');

Regex for date in format hour.minute dayName day/month

I am trying to verify str with the code below. My final goal is to allow this style of input:
18.30 Saturday_lastMatch 3/10
However, the code I have can't even work for the basic usage (98.5% str will be of this format):
19.30 Friday 15/5
var regex= /[0-9]{2}[\.:][0-9]{2} [A-Z][a-z]{4,7} [0-9]\/[0-9]{2}/;
if(!str.match(regex)) {
//"Bad format, match creation failed!");
}
What am I missing?
There are a number of problems with your regex.
The date & time matching portions at the beginning and end don't allow for 1 or 2 digit numbers as they should.
You may want to consider anchoring the regex at the beginning and end with ^ and $, respectively.
The literal dot in the character class doesn't need to be escaped.
Try this:
var regex= /^[0-9]{1,2}[.:][0-9]{1,2} [A-Z][a-z]{5,8} [0-9]{1,2}\/[0-9]{1,2}$/;
The final part of your regular expression that checks day/month needs to be expanded. It currently only matches #/##, but it should allow ##/# as well. The simplest fix would be to allow either one or two digits on either side (e.g. 12/31)
var regex= /[0-9]{2}[\.:][0-9]{2} [A-Z][a-z]{4,7} [0-9]{1,2}\/[0-9]{1,2}/;

Remove part of attribute value with jquery or javascript

There is a data parameter for a div that looks as follows:
<div data-params="[possibleText&]start=2011-11-01&end=2011-11-30[&possibleText]">
</div>
I want to remove the from the start through the end of the second date from that data-params attribute. There may or may not be text before the start and after the date after the second date.
How can I accomplish this using javascript or jQuery? I know how to get the value of the "data-params" attribute and how to set it, I'm just not sure how to remove just that part from the string.
Thank you!
Note: The dates will not always be the same.
I'd use a regular expression:
var text = $('div').attr('data-params');
var dates = text.match(/start=\d{4}-\d{2}-\d{2}&end=\d{4}-\d{2}-\d{2}/)[0]
// dates => "start=2011-11-01&end=2011-11-30"
The regular expression is not too complex. The notation \d means "match any digit" and \d{4} means "match exactly 4 digits". The rest is literal characters. So you can see how it works. Finally, that [0] at the end is because javascript match returns an array where the first element is the whole match and the rest are subgroups. We don't have any subgroups and we do want the whole match, so we just grab the first element, hence [0].
If you wanted to pull out the actual dates instead of the full query string, you can create subgroups to match by adding parenthesis around the parts you want, like this:
var dates = text.match(/start=(\d{4}-\d{2}-\d{2})&end=(\d{4}-\d{2}-\d{2})/)
// dates[0] => "start=2011-11-01&end=2011-11-30"
// dates[1] => "2011-11-01"
// dates[2] => "2011-11-30"
Here, dates[1] is the start date (the first subgroup based on parenthesis) and dates[2] is the end date (the second subgroup).
My regex skills aren't that good but this should do it
var txt = "[possibleText&]start=2011-11-01&end=2011-11-30[&possibleText]";
var requiredTxt = txt.replace(/^(.*)start=\d{4}-\d{2}-\d{2}&end=\d{4}-\d{2}-\d{2}(.*)$/, "$1$2");
I'm sure there are better ways to match your string with regex, but the $1 and $2 will put the first group and second group match into your requiredTxt stripping out the start/end stuff in the middle.
Say you have your data-params in a variable foo. Call foo.match as follows:
foo.match("[\\?&]start=([^&#]*)"); //returns ["&start=2011-11-01", "2011-11-01"]
foo.match("[\\?&]end=([^&#]*)"); //returns ["&end=2011-11-30", "2011-11-30"]

Categories