How can I convert this: NIFTY 16th JAN 12300 CE into NIFTY 16<sup>th</sup> JAN 12300 CE using jQuery?
To achieve this you can use a regular expression. To help negate the possibility of a false positive when the target string occurs within a word you can have the regex look specifically for the st, nd, rd or th strings when they follow an integer of 1 or 2 characters in length. Try this:
["NIFTY 16th JAN 12300 CE", "rd ND 21st April"].forEach(v => {
let output = v.replace(/(\d{1,2})(st|nd|rd|th)/gi, '$1<sup>$2</sup>');
console.log(output);
});
You can split th and rejoin with <sup>th</sup>
var x = "NIFTY 16th JAN 12300 CE";
var y = x.split("th").join("<sup>th</sup>");
console.log(y);
Here is the working code for the given requirement.
It works by identifying the day number, day suffix and replacing the pattern with required one.
var input = "NIFTY 16th JAN 12300 CE";
// Get the day string (Examples: 16th / 3rd)
var dayString = input.match(/[0-9]+[a-zA-Z]+/g);
// Get the day-number and day-suffix
var dayNumber = dayString.toString().match(/[0-9]+/i);
var daySuffix = dayString.toString().match(/[a-zA-Z]+/i);
// Print the output
console.log(dayNumber + "<sup>" + daySuffix + "</sup>");
Related
When used with .format('ll') I get a year, suffix, how can I fix the above to remove it?
E.g.: Jan 29, 2018 -> Jan 29
I try to use regular to replace, but it is quite complicated.
moment().format('ll').replace(new RegExp('[^\.]?' + moment().format('YYYY') + '.?'), '')
Jan 29, 2018 -> Jan 29,
reference: https://github.com/moment/moment/issues/3341
moment().format('ll')
.replace(moment().format('YYYY'), '') // remove year
.replace(/\s\s+/g, ' ')// remove double spaces, if any
.trim() // remove spaces from the start and the end
.replace(/[рг]\./, '') // remove year letter from RU/UK locales
.replace(/de$/, '') // remove year prefix from PT
.replace(/b\.$/, '') // remove year prefix from SE
.trim() // remove spaces from the start and the end
.replace(/,$/g, '')
Thanks: Localizing day and month in moment.js
How about using Javascript split :
console.log(moment().format('ll').split(',')[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
To remove the year and comma from the date string formatted with ll in moment.js, you can use the moment().format('MMM D') method, which will format the date in the format "MMM D" (e.g. "Jan 29"). Here's an example:
const moment = require('moment');
const date = moment().format('ll');
const formattedDate = moment(date, 'll').format('MMM D');
console.log(formattedDate); // Outputs e.g. "Feb 18"
In this example, we first format the date string using ll, and then use the format method with the MMM D format to extract only the month and day. The resulting string will not include the year or comma.
Alternatively, you can use the replace method with a regular expression to remove the year and comma from the date string:
const moment = require('moment');
const date = moment().format('ll');
const formattedDate = date.replace(/, \d{4}/, '');
console.log(formattedDate); // Outputs e.g. "Feb 18"
In this example, we use the replace method with a regular expression that matches a comma followed by a space and a four-digit year, and replace it with an empty string. This will remove the year and comma from the date string, leaving only the month and day.
I want to extract time from this string "Last Updated on Jul 9 2019, 3:15 pm +08"
<div id="demo"></div>
<script>
var str = "Last Updated on Jul 9 2019, 3:15 pm +08";
var result = str.match(???);
if(result) {
document.getElementById("demo").innerHTML = result;
}
</script>
or is it possible to extract the date and time but in array form like ['Jul 9 2019','3:15pm']
I'm new to using regular expression and have no idea how to formulate the pattern. Thanks in advance!
You can use a positive lookbehind to find 'on' in the string, grab everything up to the pm/am, and split on the comma and space, assuming the format is consistent:
const str = "Last Updated on Jul 9 2019, 3:15 pm +08"
console.log(str.match(/(?<=on ).*(p|a)m/)[0].split(', '))
Note, the positive lookbehind feature is not compatible with all browsers, so I would recommend using adiga's approach if compatibility is an issue.
You could use the regex /on ([^,]+),\s*(.*(?:am|pm))/ with one capturing for date and another for time
var str = "Last Updated on Jul 9 2019, 3:15 pm +08";
var result = str.match(/on ([^,]+),\s*(.*(?:am|pm))/);
result.shift();
console.log(result)
Regex demo
This can be done without using regex (assuming that the format of the time remains same like in the example you gave). Like this:
var str = "Last Updated on Jul 9 2019, 3:15 pm +08";
var onlyTime = []
onlyTime.push(str.split(' ').slice(3,6).join(' ').slice(0, -1));
onlyTime.push(str.split(' ').slice(6,8).join(''));
console.log(onlyTime)
if you what use regular expression you can use '\d{1,2}:\d{2} (am|pm)' for find the time into the string of date. With \d{1,2} you have the digit between 1 and 60, with (am|pm) you find string 'am' OR string 'pm'.
I have a requirement in my codebase where I need to trim the timestamp if it has a timezone on it.
An example of a timestamp I may receive:
"2017/08/23 12:00:00 Z"or "2017/08/23 12:00:00 +05:30"
My desired output should be:
"2017/08/23 12:00:00"or "2017/08/23 12:00:00"
You could do something like this:
var d1 = "2017/08/23 12:00:00 Z"
var d2 = "2017/08/23 12:00:00 +05:30"
var d3 = "2017/08/23 12:00:00"
const getDatePart = d => d.split(' ').reduce((r,c,i) => i <= 1 ? `${r} ${c}` : r)
console.log(getDatePart(d1))
console.log(getDatePart(d2))
console.log(getDatePart(d3))
It would do the job via String.split & reduce. It would cover the date strings with one ' ' between the date & time.
Use lastIndexOf method to find the last space and then substring to it.
var date = "2017/08/23 12:00:00 Z";
var date1 = "2017/08/23 12:00:00 +05:30";
console.log(date.substring(0, date.lastIndexOf(" ")));
console.log(date1.substring(0, date.lastIndexOf(" ")));
Assuming you process one datetime at a time, you can use this regex:
/(?<=\").*?(?:(?=Z)|(?=[+-]))/
It looks back to find a double quote, then matches any char zero or more times (non greedy), then it looks forward for either a 'Z' or plus [+] or minus [-].
I have a query that reads a date like this
var getstatusdate = $('#statusdate').val();
getstatusdate = "6/14/2016 12:00:00 AM"
Need to compare with another variable that stores date in the format below
var today = "06/14/2016"
How do I remove the time from getstatusdate and make it look like "06/14/2016"
I tried this but no luck.
var cleaneddate = getstatusdate.toDateString("MM/dd/yyyy")
In alternative, if you don't want to manage dates but manipulate strings, you can use a regex like this one;
var getstatusdate = $('#statusdate').val();
var myRegexp = ^(\d\d\/\d\d\/\d\d\d\d)(.*);
var match = myRegexp.exec(getstatusdate);
var cleaneddate = match[1];
match group 1 matches
starting string (^)
with:
2 digit
\
2 digit
\
4 digit
rest it's optional and ignored (=> in match[2])
If you are taking new Date() then like this
var dt = new Date();
var myDate = dt.getDate() + "/" +parseInt(dt.getMonth() + 1) + "/" + dt.getFullYear();
alert(dt); //Tue Jun 14 2016 21:12:07...
alert(myDate); //14/6/2016
else based on your given date, you can use split() as follow
getstatusdate = "6/14/2016 12:00:00 AM"
alert(getstatusdate.split(" ")[0]); //6/14/2016
I am using angular UI date picker to get the date. I save the date into a string variable. The problem is that I want the date to be trimmed out in a very specific format. I don't know regex, at all which I think is the right way to do this in javascript? Can somebody tell me the regex that I can write in a function that will trim the input to the specific output using native javascript only.
e.g.
Input:
Thursday sep 20-2-2015 00:00:00 GMT (+5:00) Pakistan Standard Time.
Output should be:
20-2-2015 00:00:00.
Thanks a lot!
<html>
<body>
<script language=javascript>
var txt='Thursday sep 20-2-2015 00:00:00 GMT (+5:00) Pakistan Standard Time';
var re1='.*?'; // Non-greedy match on filler
var re2='(20-2-2015)'; // DDMMYYYY 1
var re3='(\\s+)'; // White Space 1
var re4='(00:00:00)'; // HourMinuteSec 1
var p = new RegExp(re1+re2+re3+re4,["i"]);
var m = p.exec(txt);
if (m != null)
{
var ddmmyyyy1=m[1];
var ws1=m[2];
var time1=m[3];
document.write("("+ddmmyyyy1.replace(/</,"<")+")"+"("+ws1.replace(/</,"<")+")"+"("+time1.replace(/</,"<")+")"+"\n");
}
</script>
</body>
</html>
This should give you what you want:
var date = "Thursday sep 20-2-2015 00:00:00 GMT (+5:00) Pakistan Standard Time";
var expectedDate = date.match(/\d{1,2}-\d{1,2}-\d{4}\s\d{2}:\d{2}:\d{2}/g);