Match an email address which is before a specific word - javascript

I have a regex to match email addresses in javascript. Lets see an example:
var email = "aaa#bbb.com (A,B); ccc#ddd.com (C,D); eee#fff.com (E,F);";
var emails = email.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
This will return me all the emails in the var emails.
Now, I have a string:
var initials = "(A,B)";
And I would like to get only the email before the initials value;
If the var initials is "(A,B)", then I would like to get only the aaa#bbb.com email address.
Thank you a lot for your help!

JavaScript:
var input = "aaa#bbb.com (A,B); ccc#ddd.com (C,D); eee#fff.com (E,F);";
var initials = "(A,B)";
var email = input.match(new RegExp("([a-zA-Z0-9]+(?:[-._][a-zA-Z0-9]+)*#[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*)(?=\\s*" + initials.replace(/([()])/g, "\\$1") + ")"))[0];
print(email);
Output:
aaa#bbb.com
Test this code here.

Whether you have something like this "example#mail.com(A,B)" or like this "(A,B)example#mail.com", all you have to do is have the first and last part of the only capture letters. So the (A,B) should be automatically excluded for he capture of the regex.
If that is not the issue you can always grab the text returned by the regular expression and use replace to change the (A,B) to nothing, just like this:
var regexresult=str.replace("(A,B)","");
That code will remove the string if it's present, otherwise it will do nothing.

Related

javascript replace tokens using string split

Hi I have a text something like
"Welcome back ##Firstname ##Lastname. You Last accessed on ##Date"
My objective is to replace these tokens with actual values.
So what i did was
var str = "Welcome back ##Firstname ##Lastname. You Last accessed on ##Date;
var data = str.split('#');
My idea was - once i do this, my data will have an array of values something like
["Welcome back", "#FirstName" , "#LastName", "You Last accessed on" , "#Date"]
Once i have this, i can easily replace the tokens because i will know which one are properties and which one are static string. But fool i am since JS has other ideas.
it instead split it as :
["Welcome back ", "", "Firstname ", "", "Lastname. You Last accessed on ", "", "Date"]
What am i doing wrong? or what is the best way to replace tokens in a string?
I looked here. Did not like the approach much. Not a fan of curly brackets. would like to do it the "#" way - Since it will be easy for Content authors
Another regex option, split on /#(#\w+)[^\w#]+/, captures the name part while throwing off the first #, assuming the name identifiers are always made up of word characters:
var str = "Welcome back ##Firstname ##Lastname. You Last accessed on ##Date;"
var data = str.split(/#(#\w+)[^\w#]+/);
console.log(data.filter(s => s !== ""));
You can split "#" characters which are followed by "#" characters
var str = "Welcome back ##Firstname ##Lastname. You Last accessed on ##Date";
var res = str.split(/#(?=#)/);
console.log(res);
you can replace the '##' by some character followed by '#' like ',#' and then replace on that new character.
var str = "Welcome back ##Firstname ##Lastname. You Last accessed on ##Date";
var data = str.replace(/##/g, ',#').split(',');
console.log(data);
As your delemiters end with a space, may split by space:
.split(" ")
And then iterate and replace all words beginning with ##
var replaceBy={
lastname:"Doe",
name:"John"
}
var result= input.split(" ").map(function(word){
if(word[0]=="#" && word[1]=="#"){
return replaceBy[word.substr(2)] || "error";
}
return word:
}).join(" ");
However, it might be easier to suround your identifiers with delemiters e.g.:
Hi ##lastname##!
So you can do
.split("##")
And every second element is automatically an identifier.
Do this:
data = str.replace("##Firstname", "Robert").replace("##Lastname","Polson").replace('##Date','yesterday') ;

How to format string to mm/dd/yyyy with regex

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

Javascript Split String at First Numeric

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];
}

Why does this jQuery code not work?

Why doesn't the following jQuery code work?
$(function() {
var regex = /\?fb=[0-9]+/g;
var input = window.location.href;
var scrape = input.match(regex); // returns ?fb=4
var numeral = /\?fb=/g;
scrape.replace(numeral,'');
alert(scrape); // Should alert the number?
});
Basically I have a link like this:
http://foo.com/?fb=4
How do I first locate the ?fb=4 and then retrieve the number only?
Consider using the following code instead:
$(function() {
var matches = window.location.href.match(/\?fb=([0-9]+)/i);
if (matches) {
var number = matches[1];
alert(number); // will alert 4!
}
});
Test an example of it here: http://jsfiddle.net/GLAXS/
The regular expression is only slightly modified from what you provided. The global flag was removed, as you're not going to have multiple fb='s to match (otherwise your URL will be invalid!). The case insensitive flag flag was added to match FB= as well as fb=.
The number is wrapped in curly brackets to denote a capturing group which is the magic which allows us to use match.
If match matches the regular expression we specify, it'll return the matched string in the first array element. The remaining elements contain the value of each capturing group we define.
In our running example, the string "?fb=4" is matched and so is the first value of the returned array. The only capturing group we have defined is the number matcher; which is why 4 is contained in the second element.
If you all you need is to grab the value of fb, just use capturing parenthesis:
var regex = /\?fb=([0-9]+)/g;
var input = window.location.href;
var tokens = regex.exec(input);
if (tokens) { // there's a match
alert(tokens[1]); // grab first captured token
}
So, you want to feed a querystring and then get its value based on parameters?
I had had half a mind to offer Get query string values in JavaScript.
But then I saw a small kid abusing a much respectful Stack Overflow answer.
// Revised, cooler.
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match ?
decodeURIComponent(match[1].replace(/\+/g, ' '))
: null;
}
And while you are at it, just call the function like this.
getParameterByName("fb")
How about using the following function to read the query string parameter in JavaScript:
function getQuerystring(key, default_) {
if (default_==null)
default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
and then:
alert(getQuerystring('fb'));
If you are new to Regex, why not try Program that illustrates the ins and outs of Regular Expressions

How do I remove part of a string from a url using JQuery?

How do I remove everything before /post in this string below and add my own address using Javascript/JQuery
showLogo=false&showVersionInfo=false&dataFile=/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500
I want it to appear like this:
http://mydomain.com/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500
var str = 'showLogo=false&showVersionInfo=false&dataFile=/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500';
str = 'http://mydomain.com' + str.split('&dataFile=')[1];
Example: http://jsfiddle.net/52z2z/
Here it splits the string on '&dataFile=', gets the last item in the resulting Array, and concatenates it do your domain.
You could also do this in Javascript using regular expressions:
var url = "showLogo=false&showVersionInfo=false&dataFile=/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500";
var matches = url.match(/dataFile=(.*)/);
var what_you_need = "http://mydomain.com" + matches[1];
HTH

Categories