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
Related
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);
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);
I have been struggling with this particular regular expression and was wondering if anyone can help. I have an input field that allows users to enter text and if a user enters 01201990 I have a method that converts it to 01/20/19/90 The problem is I don't want the regular expression to continue after the mm/dd/ my end result would look like this 01/20/1990 Any help would be amazing.
var tmparray = [];
tmparray.push(
tmp.model
// here is where I dont know how to prevent the regex
// from continuing after 01/20/
.match(new RegExp('.{1,2}', 'g'))
.join("/")
);
tmp.model = tmparray;
console.log(tmp.model);
You can use replace() in this case
document.write('19101992'.replace(/(\d{2})(\d{2})(\d{4})/, '$1/$2/$3'))
Your code will be like
var tmparray = [];
tmparray.push(
tmp.model
// here is where I dont know how to prevent the regex
// from continuing after 01/20/
.replace(/(\d{2})(\d{2})(\d{4})/g, '$1/$2/$3')
);
tmp.model = tmparray;
console.log(tmp.model);
why not just match on:
/(\d{2})(\d{2})(\d{4})/
then dd/mm/yyyy is:
$1/$2/$3
(I can't see why you'd match {1,2} since you can't tell the difference between 1/11/1990 and 11/1/1990 and in either case would get 11/11/990...)
Try using String.prototype.slice() , String.prototype.concat()
var str = "01201990" , d = "/"
, res = str.slice(0,2).concat(d + str.slice(2,4)).concat(d + str.slice(4));
console.log(res)
use regex [0-9]{2}(?=(?:[0-9]{4})). for more information please check link https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch06s12.html
I have function that is supposed to "clean" a string and i'd like to use replace() to do that, but I can't figure out why the following code is not working when the text comes from an input[text].
for instance :
console.log(getCleanText("ééé")); // works fine, it displays : eee
but
// my_id is an input with type="text"
var my_text = document.getElementById("my_id").value
console.log(getCleanText(my_text)); // doesn't work at all, it displays : ééé
the function code is :
function getCleanText(some_text) {
var clean_text = some_text.toLowerCase();
clean_text = clean_text.replace("é", "e");
clean_text = clean_text.split("é").join("e"); // give it another try
return clean_text;
}
any idea ?
I'm willing to bet your problem lies in a misunderstanding of Unicode.
é
é
Those two characters above are two different characters. The first is the letter e, with an accent character (U+0301). The other is a single character, U+00E9.
You need to ensure you're replacing both versions.
I think the character "é" from element value is the different from the "é" constant. To resolve that you can take look at the int value of the input.
var inputEValue = document.getElementById("my_id").charCodeAt(0);
var constantEValue = "é".charCodeAt(0);
Then you will be able to detect what characters you are replacing.
If you want to just remove accents from text, take look at the question Remove accents/diacritics in a string in JavaScript
Try this:
function getCleanText(old_string)
{
var new_string = old_string.toLowerCase();
return new_string.replace(/é/g, 'e');
}
Ed: beaten by the Robert. For reference, see here: What are useful JavaScript methods that extends built-in objects?
Try this:
function cleanText(text) {
var re = new RegExp(/\u0301|\u00e9/g);
return text.replace(re, "e").toLowerCase();
}
cleanText("éééé")
--
Updated to use the proposed UniCode chars by Matt Grande
What is the output of
var my_text = document.getElementById("my_id").value; ?
Depending on your html, you might need to use other functions to get the data. e.g
var my_text = document.getElementById("my_id").innerHTML;
http://jsbin.com/obAmiPe/5/edit?html,js,console,output
I am trying to split a UK postcode string to only include the initial letters. For example, 'AA1 2BB' would become 'AA.'
I was thinking something like the below.
var postcode = 'AA1 2BB';
var postcodePrefix = postcode.split([0-9])[0];
This does not actually work, but can someone help me out with the syntax?
Thanks for any help.
You can try something like this:
var postcode = 'AA1 2BB';
var postcodePrefix =postcode.split(/[0-9]/)[0];
Alternatively, you could use a regex to simply find all alphabetic characters that occur at the beginning of the string:
var postcode = 'AA1 2BB';
var postcodePrefix = postcode.match(/^[a-zA-Z]+/);
If you want any initial characters that are non numeric, you could use:
var postcodePrefix = postcode.match(/^[^0-9]+/);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
"AA1 2BB".split(/[0-9]/)[0];
or
"AA1 2BB".split(/\d/)[0];
var m = postcode.match(/([^\d]*)/);
if (m) {
var prefix = m[0];
}