Im currently developing a posting [like What's on your mind] feature where im using twemoji plugin for emojis.
For some security reasons, i have to convert the emoji into its alt code/image filename before it stores to the database.
And convert it back to image when its being displayed on the feeds.
In my case I use [emoji=filename.png]
for example i have this string:
var string = "[emoji=1f938.png] [emoji=1f938-200d-2642-fe0f.png] [emoji=26f9-fe0f.png]";
string.replace(/-fe0f.png/g, '.png')
.replace(/\[emoji=(.*?)\]/g,'<img src="https://example.net/images/$1">');
the snippet above is working fine, but the only problem is it removes All -fe0f.png in the filename which causes some broken image.
What I want to achive is to remove the -fe0f.png part only when the filename length is <= 14. or maybe if the file name is consist of something like this: (char)-fe0f.png , but if it has more than (char) like (char)-(char)-(char)-fe0f.png, it should still remain the same..
the result should be:
from
[emoji=1f938.png] [emoji=1f938-200d-2642-fe0f.png] [emoji=26f9-fe0f.png]
to
[emoji=1f938.png] [emoji=1f938-200d-2642-fe0f.png] [emoji=26f9.png]
UPDATE:
I just noticed now that there are filenames like this 30-fe0f-20e3.png
but it needs to remove -fe0f in the middle.
so instead of [emoji=30-fe0f-20e3.png],
i need to have [emoji=30-20e3.png]
The file name length limit is equal to fourteen. Thus, there should be "nine" characters before the "-fe0f"
[^=] means all characters except "="
<![^=])a means there must not "=" before the "a"
<![^=]{9})a means it must not has a "=" character during the nine characters before the letter "a".
(?<![^=]{9})-fe0f.png means it must not has a "=" character during the nine characters before the "-fe0f.png".
So your new code should be like the below:
var string = "[emoji=1f938.png] [emoji=1f938-200d-2642-fe0f.png] [emoji=26f9-fe0f.png]";
string.replace(/(?<![^=]{9})-fe0f.png/g, '.png')
.replace(/\[emoji=(.*?)\]/g,'<img src="https://example.net/images/$1">');
Replacing the data in the example string:
const regex = /(\[emoji=[^\s\]\[]{0,13})-fe0f(\.png)/g;
let string = "[emoji=1f938.png] [emoji=1f938-200d-2642-fe0f.png] [emoji=26f9-fe0f.png]";
string = string.replace(regex, '$1$2');
console.log(string);
You can do the replacement in one replace call with a match and a capture group, matching 0-13 characters after emoji=
\[emoji=([^\s\]\[]{0,13})-fe0f\.png]
The pattern matches:
\[emoji= Match [emoji=
( Capture group 1
[^\s\]\[]{0,13} Match 0-13 times a non whitespace char except for [ and ]
) Close group 1
-fe0f\.png] Match literally (note to escape the dot)
regex demo
const regex = /\[emoji=([^\s\]\[]{0,13})-fe0f\.png]/g;
let string = "[emoji=1f938.png] [emoji=1f938-200d-2642-fe0f.png] [emoji=26f9-fe0f.png]";
string = string.replace(regex, '<img src="https://example.net/images/$1.png">');
console.log(string);
This should do it if you are just trying to not replace for greater than 14 chars.
if (string.length > 14) {
// do your replace here
}
Now, not sure if you are suggesting that if there's more than one "-" that you don't want to replace either.
Related
I want to remove some text from string or integer using javascipt or jquery..
I have string "flow-[s/c]", "flow-max[s/c]","flow-min[s/c]", "Usage-[s/c]", "temperature"
And I want for each :
"flow", "flow-max","flow-min", "Usage", "temperature"
As you can see. I want to remove all the data after - found expect flow-max and flow-min
What I am doing :
var legendName = $(textElement).text().toLowerCase().replace(" ", "-");
Taking the legend Name example : "flow-[s/c]", "flow-max[s/c]"
var displayVal = legendName.split('-')[0];
remove all the data after - found
But I am not able to add condition for flow-max because at this case I will be having two - and two place like flow-min-[s/c]
var displayVal = $(textElement).text().replace(/\-?\[s\/c\]/, "");
The code /\-?\[s\/c\]/ is a regular expression, where:
/ at the start and end are the delimiters of the expression.
\ is an escape character, indicating that the following character should be taken literally (in our example we need it in front of -, [, / and ] because those are control character for regular expressions).
? means the previous character is optional.
So it replaces an optional dash (-) followed by the text [s/c], with an empty string.
Just use this simple regex /(max|min)\[.*?]|-\[.*?]/g. The regex is simple, if you see what it does separately.
The logic has been separated by | operator.
legendName = legendName.replace(/(max|min)\[.*?]|-\[.*?]/, "$1");
You can use lastoccur = legendName.lastIndexOf("-"); to find the last occur of "-" and then split your string.
Reference: http://www.w3schools.com/jsref/jsref_lastindexof.asp
Any working Regex to find image url ?
Example :
var reg = /^url\(|url\(".*"\)|\)$/;
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
var string2 = 'url(http://domain.com/randompath/random4509324041123213.jpg)';
console.log(string.match(reg));
console.log(string2.match(reg));
I tied but fail with this reg
pattern will look like this, I just want image url between url(" ") or url( )
I just want to get output like http://domain.com/randompath/random4509324041123213.jpg
http://jsbin.com/ahewaq/1/edit
I'd simply use this expression:
/url.*\("?([^")]+)/
This returns an array, where the first index (0) contains the entire match, the second will be the url itself, like so:
'url("http://domain.com/randompath/random4509324041123213.jpg")'.match(/url.*\("?([^")]+)/)[1];
//returns "http://domain.com/randompath/random4509324041123213.jpg"
//or without the quotes, same return, same expression
'url(http://domain.com/randompath/random4509324041123213.jpg)'.match(/url.*\("?([^")]+)/)[1];
If there is a change that single and double quotes are used, you can simply replace all " by either '" or ['"], in this case:
/url.*\(["']?([^"')]+)/
Try this regexp:
var regex = /\burl\(\"?(.*?)\"?\)/;
var match = regex.exec(string);
console.log(match[1]);
The URL is captured in the first subgroup.
If the string will always be consistent, one option would be simply to remove the first 4 characters url(" and the last two "):
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
// Remove last two characters
string = string.substr(0, string.length - 2);
// Remove first five characters
string = string.substr(5, string.length);
Here's a working fiddle.
Benefit of this approach: You can edit it yourself, without asking StackOverflow to do it for you. RegEx is great, but if you don't know it, peppering your code with it makes for a frustrating refactor.
I am currently using the following JavaScript code:
concatedSubstring.replace(/\//g, '-').replace(/[A-Za-z]/g, function(c){
return c.toUpperCase().charCodeAt(0)-64;
});
...to take input in the format "1234/A", "22/B", etc. and output "1234-1" , "22-2", etc.
That is, / becomes -, and the letters become integers with A = 1, B = 2, etc.
I would like to change this so that if the input doesn't contain a "/" the output will still insert a "-" in the spot where the "/" should've been. That is, the input "1234A" should output "1234-1", or "22B" should output "22-2", etc.
The following should work even for inputs containing more than one of your number/letter pattern:
var input = "1234/B 123a 535d";
var replaced = input.replace(/(\d+)(\/?)([A-Za-z])/g, function(m,p1,p2,p3) {
return p1 + "-" + (p3.toUpperCase().charCodeAt(0)-64);
});
alert(replaced); // "1234-2 123-1 535-4"
The regex:
/(\d+)(\/?)([A-Za-z])/g
...will match one or more digits followed by an optional forward slash followed by a single letter, capturing each of those parts for later use.
If you pass a callback to .replace() then it will be called with arguments for the full match (which I'm ignoring for your requirement) and also for any sub-matches (which I use).
str = "1234/B"; or str = "1234B";
str.replace(/(\/[A-Z])|([A-Z])/g,"-"+parseInt(str.charCodeAt(str.indexOf(str.match(/[A-Z]/g)))-64))
You can also .replace(/([0-9])([a-zA-Z])/g,"$1-$2"): this turns a number adjacent to a letter into numberDASHletter, using backreferences (the $1 refers to whatever was in the first set of brackets, $2 to whatever was in the second set of brackets).
string str contains somewhere within it http://www.example.com/ followed by 2 digits and 7 random characters (upper or lower case). One possibility is http://www.example.com/45kaFkeLd or http://www.example.com/64kAleoFr. So the only certain aspect is that it always starts with 2 digits.
I want to retrieve "64kAleoFr".
var url = str.match([regex here]);
The regex you’re looking for is /[0-9]{2}[a-zA-Z]{7}/.
var string = 'http://www.example.com/64kAleoFr',
match = (string.match(/[0-9]{2}[a-zA-Z]{7}/) || [''])[0];
console.log(match); // '64kAleoFr'
Note that on the second line, I use the good old .match() trick to make sure no TypeError is thrown when no match is found. Once this snippet has executed, match will either be the empty string ('') or the value you were after.
you could use
var url = str.match(/\d{2}.{7}$/)[0];
where:
\d{2} //two digits
.{7} //seven characters
$ //end of the string
if you don't know if it will be at the end you could use
var url = str.match(/\/\d{2}.{7}$/)[0].slice(1); //grab the "/" at the begining and slice it out
what about using split ?
alert("http://www.example.com/64kAleoFr".split("/")[3]);
var url = "http://www.example.com/",
re = new RegExp(url.replace(/\./g,"\\.") + "(\\d{2}[A-Za-z]{7})");
str = "This is a string with a url: http://www.example.com/45kaFkeLd in the middle.";
var code = str.match(re);
if (code != null) {
// we have a match
alert(code[1]); // "45kaFkeLd"
}
The url needs to be part of the regex if you want to avoid matching other strings of characters elsewhere in the input. The above assumes that the url should be configurable, so it constructs a regex from the url variable (noting that "." has special meaning in a regex so it needs to be escaped). The bit with the two numbers and seven letter is then in parentheses so it can be captured.
Demo: http://jsfiddle.net/nnnnnn/NzELc/
http://www\\.example\\.com/([0-9]{2}\\w{7}) this is your pattern. You'll get your 2 digits and 7 random characters in group 1.
If you notice your example strings, both strings have few digits and a random string after a slash (/) and if the pattern is fixed then i would rather suggest you to split your string with slash and get the last element of the array which was the result of the split function.
Here is how:
var string = "http://www.example.com/64kAleoFr"
ar = string.split("/");
ar[ar.length - 1];
Hope it helps
Let's say we have a string in JavaScript "This is a nice website - http://stackoverflow.com". I want to extract the URL along with the three preceding characters (space dash space) using RegExp and attach the extracted string to a variable.
var string = "This is a nice website - http://stackoverflow.com";
var reg = ""; //no idea how to write this regexp for extracting url and three preceding chars
// and after some magic I would get
var extracedString = " - http://www.stackoverflow.com";
Anyone? Thanks.
var extractedString = string.replace(/^.*(...http:.+)$/, "$1");
if (extractedString == string) {
alert("No match");
}
The dot . matches every character, so three dots match three arbitrary characters. The ^ and $ match start and end of the string.
Note, that this won't work for
more than one URL
HTTPS, mailto, FTP, SSH, ... (although you can simply expand it, like this: (https?|ftp|ssh))