Javascript using regular expression to get date in middle of object - javascript

I have this object "FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020" and need to extract the FROM_DATE value 2/9/2020. I am trying to use replace, to replace everything before and after the from date with an empty string, but I'm not sure how to get both sides of the value.
at the moment I can remove everything up until the date value with this... /.*FROM_DATE":"/ but how can I now remove the final part of the object?
Thanks

If you need to make it with replace, just use:
const input = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
const date = input.replace(/^.*"FROM_DATE":"([\d/]+)".*$/, '$1');
Now you can use date with just the date in it...

In a second time you could remove /",.*/, but this seems too much heuristic to me.
You'd better just catch the first capturing group from the following regex:
/FROM_DATE":"([0-9][0-9]?\/[0-9][0-9]?\/[0-9][0-9][0-9][0-9])"/
let str = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
let pattern = /FROM_DATE":"([0-9][0-9]?\/[0-9][0-9]?\/[0-9][0-9][0-9][0-9])"/
alert(str.match(pattern)[1]);

Your sample string looks very much like JSON. So much so in fact that you could just wrap it in braces, parse it as and object, and get the value of the FROM_DATE.
EG:
function almostJsonStringToObject(str) {
return JSON.parse('{' + str + '}');
}
var str = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
var obj = almostJsonStringToObject(str);
var fromdate = obj.FROM_DATE;
console.log(fromdate);

Related

change string new date to date

I have string date like
'new Date(0,0,0,11,13,16)'
and want to change it to
new Date(0,0,0,11,13,16)
anyone have an idea on it.
thanks
var str = 'new Date(0,0,0,11,13,16)';
var str1 = str.match(/\(.*\)/g)[0];
str1 = str1.replace('(', '');
str1 = str1.replace(')', '');
var dateArr = str1.split(',');
var updatedDate = new
Date(dateArr[0],dateArr[1],dateArr[2],dateArr[3],dateArr[4],dateArr[5]);
console.log(updatedDate);
Use regex to solve this problem by matching only numbers. match will return an array of numbers so use the spread operator to set all the parameters to Date.
const res = new Date(...'new Date(0,0,0,11,13,16)'.match(/[0-9]+/g));
console.log(res);
Theoretically you could use the eval function for that.
Depending on the use, this does propose some security risk though. Read more about this here
If it's possible I would suggest you use another form of date string, e.g. "yyyy-mm-dd" (2019-02-17) and parse it to a date object using the new Date(dateString) constructor (new Date('2019-01-17')).

search a regex and filter it

Hi i am try to find a variable date in a string with a regex and after this i want to save the date in a new variable my code looks like:
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
if(valide.test(text) === true){
}
how can i put the found date (02.02.1989) in a new variable
You can create groups in your Regex expression (just put the values you want between parenthesis) and then use this to get the specific group value.
Note, however, I think your regex is wrong... it seems you end with 1 plus 4 digits
You can use match on a string:
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
console.dir(text.match(valide)) // ["02.02.1989"]
if(valide.test(text) === true){
}
Using REGEXP function match you can extract the part that match your regular expression.
After this you will get an object. In this case i turn it into a string so you can do a lot more things with it.
var myDate = text.match(valide).toString();
Hope this helps :>
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
if(valide.test(text) === true){
var myDate = text.match(valide).toString();
console.log(myDate)
}
You can use match for that:
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
var foundDate = text.match(valide);
console.log(foundDate);
Also, you can make the regex a bit simpler if you switch the ([./-]) to ([-.]), because - is considered a literal match if it comes first inside a character class.
You could do something like this.
var result = text.match(valide)
Here is a reference for the match method String.prototype.match

Using RegExp to substring a string at the position of a special character

Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);

Problems in replacing symbol to nothing

How can I solve this error, which i keep getting, here it is:
TypeError: date.replace is not a function
date = date.replace("*", "");
And this is all code:
var date = cellElement.innerHTML.split("/");
date = date.replace("*", "");
alert(date);
cellElement.innerHTML looks like this
2015/Rgs/01*
Something is wrong with that replace.
How can I solve it?
Because date is an array, you cannot use string methods on it. When you use split() on string, array is returned.
To replace * symbol from string, you need to first replace it and then split it by /.
var date = cellElement.innerHTML.replace("*", "").split("/");
alert(date);
You are using the wrong type of variable.
method replace works only with type String.
try this:
var date = cellElement.innerHTML.split("/");
var date2string = date.toString();
date = date2string.replace("*", "");
or:
var date = cellElement.innerHTML.replace("*","");
var result = date.split("/");
alert(result);

group parts of a string into an array element

If I have a string... abcdefghi
and I want to use regex to load every elemnent into an array but I want to be able to stick anything connected by plus sign into the same element... how to do that?
var mystring = "abc+d+efghi"
output array ["a","b","cde","f","g","h","i"]
One way to do it:
var re = /([^+])(?:\+[^+])*/g;
var str = 'abcd+e+fghi';
var a = str.match(re).map(function (s) { return s.replace(/\+/g, ''); });
console.log(a);
The value of a[3] should now be 'def'.
http://jsfiddle.net/rbFwR/2
You can use this expression, to produce [a][b][c+d+e][f][g][h][i].
mystring.split ("(.\+)*.")
Next, replace any + characters with empty on the resulting list.
mystring.split("\\+")
Click here for more information.

Categories