Regex to wrap email address in mailto from a string - javascript

Want to turn some text email#address.com into some text email#address.com
Below is the regex I'm using in replace:
'some text email#address.com'.replace(/([a-zA-Z0-9_\.\-]+)#(([[0-9]{1,3}' + '\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.' + ')+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)/gi, '<a href='mailto:$1'>$1</a>');
The regex is not working properly, please help.

As suggested by #Toto, you can use this regex \S+#\S+ to include every possible (and non-possible) characters in the email excluding the space.
(\S+#\S+)
If you want to include only English characters a-z, numbers 0-9, dots ., underscores _, and dashes - . You can do it this way:
([\w\.\-]+#\w+\.\w+)
If you want to add to the previous one every possible character from any language à è ì ò ù, and at the same time, exclude special characters % ^ & *, you can use \pL as follows:
([\w\.\-\pL]+#\w+\.\w+)
Demo for the last Regex:
var Email = "some text email#address.com.";
Email = Email.replace(/([\w\.\-\pL]+#\w+\.\w+)/g, '<a href=mailto:$1>$1</a>');
document.write (Email);

You can use replacer function of replace() function:
var str = "some text email#address.com";
var regex = /\w+#\w+\.\w+/gi;
var replacedString = str.replace( regex, function(match){
return ''+match+'';
});
console.log( replacedString );

Old question, but I was doing something like this in my code and had to fix a bug where the email address is already wrapped in a mailto link. This was my simple solution to that problem:
var rx = /([mailto:\w.\-pL]+#\w+.[\w.\-pL]+)/gi
return str.replace(rx, function (match) {
return (match.indexOf('mailto') === 0) ? match : `${match}`
})
The regex optionally matches "mailto:" and the replacer function checks to see if it is in the match, and returns it unmodified if so.
Maybe this will help a fellow google-passer-by.

Related

Is there a javascript method to recognize a string even if the words are out of order? [duplicate]

I would like to find all the matches of given strings (divided by spaces) in a string.
(The way for example, iTunes search box works).
That, for example, both "ab de" and "de ab" will return true on "abcde" (also "bc e a" or any order should return true)
If I replace the white space with a wild card, "ab*de" would return true on "abcde", but not "de*ab".
[I use * and not Regex syntax just for this explanation]
I could not find any pure Regex solution for that.
The only solution I could think of is spliting the search term and run multiple Regex.
Is it possible to find a pure Regex expression that will cover all these options ?
Returns true when all parts (divided by , or ' ') of a searchString occur in text. Otherwise false is returned.
filter(text, searchString) {
const regexStr = '(?=.*' + searchString.split(/\,|\s/).join(')(?=.*') + ')';
const searchRegEx = new RegExp(regexStr, 'gi');
return text.match(searchRegEx) !== null;
}
I'm pretty sure you could come up with a regex to do what you want, but it may not be the most efficient approach.
For example, the regex pattern (?=.*bc)(?=.*e)(?=.*a) will match any string that contains bc, e, and a.
var isMatch = 'abcde'.match(/(?=.*bc)(?=.*e)(?=.*a)/) != null; // equals true
var isMatch = 'bcde'.match(/(?=.*bc)(?=.*e)(?=.*a)/) != null; // equals false
You could write a function to dynamically create an expression based on your search terms, but whether it's the best way to accomplish what you are doing is another question.
Alternations are order insensitive:
"abcde".match(/(ab|de)/g); // => ['ab', 'de']
"abcde".match(/(de|ab)/g); // => ['ab', 'de']
So if you have a list of words to match you can build a regex with an alternation on the fly like so:
function regexForWordList(words) {
return new RegExp('(' + words.join('|') + ')', 'g');
}
'abcde'.match(['a', 'e']); // => ['a', 'e']
Try this:
var str = "your string";
str = str.split( " " );
for( var i = 0 ; i < str.length ; i++ ){
// your regexp match
}
This is script which I use - it works also with single word searchStrings
var what="test string with search cool word";
var searchString="search word";
var search = new RegExp(searchString, "gi"); // one-word searching
// multiple search words
if(searchString.indexOf(' ') != -1) {
search="";
var words=searchString.split(" ");
for(var i = 0; i < words.length; i++) {
search+="(?=.*" + words[i] + ")";
}
search = new RegExp(search + ".+", "gi");
}
if(search.test(what)) {
// found
} else {
// notfound
}
I assume you are matching words, or parts of words. You want space-separated search terms to limit search results, and it seems you intend to return only those entries which have all the words that the user supplies. And you intend a wildcard character * to stand for 0 or more characters in a matching word.
For example, if the user searches for the words term1 term2, you intend to return only those items which have both words term1 and term2. If the user searches for the word term*, it would match any word beginning with term.
There are suitable regular expressions which are equivalent to this search language and can be generated from it.
A simple example, the word term, can be asserted in regex by converting to \bterm\b. But two or more words which must match in any order require lookahead assertions. Using extended syntax, the equivalent regex is:
(?= .* \b term1 \b )
(?= .* \b term2 \b )
The asterisk wildcard can be asserted in regex with a character class followed by asterisk. The character class identifies which letters you consider to be part of word. For example, you might find that [A-Za-z0-9]* fits the bill.
In short, you might be satisfied if you convert an expression such as:
foo ba* quux
to:
(?= .* \b foo \b )
(?= .* \b ba[A-Za-z0-9]* \b )
(?= .* \b quux \b )
That is a simple matter of search and replace. But do be careful to sanitize the input string to avoid injection attacks by removing punctuation, etc.
I think you may be barking up the wrong tree with RegEx. What you might want to look at is the Levenshtein distance of two input strings.
There's a Javascript implementation here and a usage example here.

JavaScript RegEx: match all minuses that are not at start or end of string for currency input

For a currency input I want to replace all minus input that is not at the start of the string or, when it is the last character, is not preceded by a comma.
In the input event I'm already calling a replace with a simple regex for some other invalid input:
input.replace(/[^0-9\.\,\-]/g, '')
.replace('.', ',');
It would be great if I could extend this regex to also strip the invalid minuses.
Some examples of desired behavior:
50-50 -> 5050
50,00- -> 50,00
-5-0,- -> -50,-
Edit: double minus at the end or start should also be stripped.
--50,00-> -50,00
50,-- -> 50,-
I figured I could start with a positive lookahead -(?=.), but that still matches the first character.
Additionally, I found this post that pretty much does the opposite (minuses are not allowed at start and end), but that would still match the whole string. Not the sepatate minuses.
Any help would be appreciated.
Use the following approach with specific regex pattern:
var replaceHyphen = function (str) {
return str.replace(/(\d)-|(-)-/g, '$1$2');
};
console.log(replaceHyphen('50-50'));
console.log(replaceHyphen('50,00-'));
console.log(replaceHyphen('-5-0,-'));
console.log(replaceHyphen('--50,00'));
console.log(replaceHyphen('50,--'));
Is a function ok? This should do the trick:
function removeMinus(str) {
var prefix = str.startsWith("-") ? "-" : "";
var postfix = str.endsWith(",-") ? "-" : "";
return prefix + str.split("-").join("") + postfix
}
You could use word boundary \b to do that.
RegExp Boundaries
\b
Matches a word boundary. This is the position where a word character is not followed or preceeded by another word-character, such as between a letter and a space...
https://regex101.com/r/YzCiEx/1
var regex = /\b-+\b/g;
console.log("50-50".replace(regex, ''))
console.log("50,00".replace(regex, ''))
console.log("-5-0,-".replace(regex, ''))
console.log("-5------6-".replace(regex, ''))
console.log("-6--66-6,-".replace(regex, ''))

regex: Match when between text but not between digits

Please help.
I need a regular expression (to be used in javascript) to replace "." with "#" in a text containing Unicode characters.
Replacement takes place only when "." appears between text but not between digits.
Input: "ΦΨ. ABC. DEF. 123.456"
Desired output: "ΦΨ# ABC# DEF# 123.456"
Any suggestions?
You can use capturing groups in the regex and use back-references to obtain the required result:
var re = /(\D)\.(\D)/g;
var str = 'ΦΨ. ABC. DEF. 123.456';
var subst = '$1#$2';
result = str.replace(re, subst);
alert(result);
Regex Explanation:
\D - A non-digit character
\. - A literal dot
The non-digit characters are captured into groups, and then inserted back with the help of $1 and $2 back-references.
try this:
var str = "ΦΨ. ABC. DEF. 123.456";
str.replace(/[^\d.]+\.[^\d]/g, function (m) {
return m.replace('.', '#')
});

JavaScript regular expression to match hyphenated words?

I'd like a JavaScript regular expression that can match a string either at the start of another string, or after a hyphen in the string.
For example, "milne" and "lee" and "lees" should all match "Lees-Milne".
This is my code so far:
var name = "Lees-Milne";
var text = "lee";
// I don't know what 'text' is ahead of time, so
// best to use RegExp constructor.
var re = RegExp("^" + text | "-" + text, "i");
alert(re.exec(name.toLowerCase()));
However, this returns null. What am I doing wrong?
You could also use:
var re = RegExp("(?:^|-)" + text, "i");
Don't forget to escape regex meta characters in text if it's not an expression it self.
JavaScript has no built in function for that, but you could use:
function quotemeta(str){
return str.replace(/[.+*?|\\^$(){}\[\]-]/g, '\\$&');
}

Remove ALL white spaces from text

$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");
This is a snippet from my code. I want to add a class to an ID after getting another ID's text property. The problem with this, is the ID holding the text I need, contains gaps between the letters.
I would like the white spaces removed. I have tried TRIM()and REPLACE() but this only partially works. The REPLACE() only removes the 1st space.
You have to tell replace() to repeat the regex:
.replace(/ /g,'')
The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
If you want to match all whitespace, and not just the literal space character, use \s instead:
.replace(/\s/g,'')
You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:
.replaceAll(/\s/g,'')
.replace(/\s+/, "")
Will replace the first whitespace only, this includes spaces, tabs and new lines.
To replace all whitespace in the string you need to use global mode
.replace(/\s/g, "")
Now you can use "replaceAll":
console.log(' a b c d e f g '.replaceAll(' ',''));
will print:
abcdefg
But not working in every possible browser:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
Regex for remove white space
\s+
var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);
or
[ ]+
var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);
Remove all white space at begin of string
^[ ]+
var str = " Visit Microsoft!";
var res = str.replace(/^[ ]+/g, "");
console.log(res);
remove all white space at end of string
[ ]+$
var str = "Visit Microsoft! ";
var res = str.replace(/[ ]+$/g, "");
console.log(res);
var mystring="fg gg";
console.log(mystring.replaceAll(' ',''))
** 100% working
use replace(/ +/g,'_'):
let text = "I love you"
text = text.replace( / +/g, '_') // replace with underscore ('_')
console.log(text) // I_love_you
Using String.prototype.replace with regex, as mentioned in the other answers, is certainly the best solution.
But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split and String.prototype.join:
const text = ' a b c d e f g ';
const newText = text.split(/\s/).join('');
console.log(newText); // prints abcdefg
I don't understand why we need to use regex here when we can simply use replaceAll
let result = string.replaceAll(' ', '')
result will store string without spaces
let str = 'a big fat hen clock mouse '
console.log(str.split(' ').join(''))
// abigfathenclockmouse
Use string.replace(/\s/g,'')
This will solve the problem.
Happy Coding !!!
simple solution could be : just replace white space ask key value
val = val.replace(' ', '')
Use replace(/\s+/g,''),
for example:
const stripped = ' My String With A Lot Whitespace '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'
Well, we can also use that [^A-Za-z] with g flag for removing all the spaces in text. Where negated or complemente or ^. Show to the every character or range of character which is inside the brackets. And the about g is indicating that we search globally.
let str = "D S# D2m4a r k 23";
// We are only allowed the character in that range A-Za-z
str = str.replace(/[^A-Za-z]/g,""); // output:- DSDmark
console.log(str)
javascript - Remove ALL white spaces from text - Stack Overflow
Using .replace(/\s+/g,'') works fine;
Example:
this.slug = removeAccent(this.slug).replace(/\s+/g,'');
function RemoveAllSpaces(ToRemove)
{
let str = new String(ToRemove);
while(str.includes(" "))
{
str = str.replace(" ", "");
}
return str;
}

Categories