Replace letters with integer and place "-" (dash) with it - javascript

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).

Related

Having hard time with jQuery and replace string value

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.

How to write regexp for finding :smile: in javascript?

I want to write a regular expression, in JavaScript, for finding the string starting and ending with :.
For example "hello :smile: :sleeping:" from this string I need to find the strings which are starting and ending with the : characters. I tried the expression below, but it didn't work:
^:.*\:$
My guess is that you not only want to find the string, but also replace it. For that you should look at using a capture in the regexp combined with a replacement function.
const emojiPattern = /:(\w+):/g
function replaceEmojiTags(text) {
return text.replace(emojiPattern, function (tag, emotion) {
// The emotion will be the captured word between your tags,
// so either "sleep" or "sleeping" in your example
//
// In this function you would take that emotion and return
// whatever you want based on the input parameter and the
// whole tag would be replaced
//
// As an example, let's say you had a bunch of GIF images
// for the different emotions:
return '<img src="/img/emoji/' + emotion + '.gif" />';
});
}
With that code you could then run your function on any input string and replace the tags to get the HTML for the actual images in them. As in your example:
replaceEmojiTags('hello :smile: :sleeping:')
// 'hello <img src="/img/emoji/smile.gif" /> <img src="/img/emoji/sleeping.gif" />'
EDIT: To support hyphens within the emotion, as in "big-smile", the pattern needs to be changed since it is only looking for word characters. For this there is probably also a restriction such that the hyphen must join two words so that it shouldn't accept "-big-smile" or "big-smile-". For that you need to change the pattern to:
const emojiPattern = /:(\w+(-\w+)*):/g
That pattern is looking for any word that is then followed by zero or more instances of a hyphen followed by a word. It would match any of the following: "smile", "big-smile", "big-smile-bigger".
The ^ and $ are anchors (start and end respectively). These cause your regex to explicitly match an entire string which starts with : has anything between it and ends with :.
If you want to match characters within a string you can remove the anchors.
Your * indicates zero or more so you'll be matching :: as well. It'll be better to change this to + which means one or more. In fact if you're just looking for text you may want to use a range [a-z0-9] with a case insensitive modifier.
If we put it all together we'll have regex like this /:([a-z0-9]+):/gmi
match a string beginning with : with any alphanumeric character one or more times ending in : with the modifiers g globally, m multi-line and i case insensitive for things like :FacePalm:.
Using it in JavaScript we can end up with:
var mytext = 'Hello :smile: and jolly :wave:';
var matches = mytext.match(/:([a-z0-9]+):/gmi);
// matches = [':smile:', ':wave:'];
You'll have an array with each match found.

Finding image url via using Regex

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.

Regex in javascript complex

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

Javascript Regex- replace sequence of characters with same number of another character

I'm trying to replace part of a string with the same number of dummy characters in JavaScript, for example: '==Hello==' with '==~~~~~=='.
This question has been answered using Perl and PHP, but I can't get it to work in JavaScript. I've been trying this:
txt=txt.replace(/(==)([^=]+)(==)/g, "$1"+Array("$2".length + 1).join('~')+"$3");
The pattern match works fine, but the replacement does not - the second part adds '~~' instead of the length of the pattern match. Putting the "$2" inside the parentheses doesn't work. What can I do to make it insert the right number of characters?
Use a function for replacement instead:
var txt = "==Hello==";
txt = txt.replace(/(==)([^=]+)(==)/g, function ($0, $1, $2, $3) {
return $1 + (new Array($2.length + 1).join("~")) + $3;
});
alert(txt);
//-> "==~~~~~=="
The issue with the expression
txt.replace(/(==)([^=]+)(==)/g, "$1"+Array("$2".length + 1).join('~')+"$3")
is that "$2".length forces $2 to be taken as a string literal, namely the string "$2", that has length 2.
From the MDN docs:
Because we want to further transform the result of the match before the final substitution is made, we must use a function.
This forces evaluation of the match before the transformation.
With an inline function as parameter (and repeat) -- here $1, $2, $3 are local variables:
txt.replace(/(==)([^=]+)(==)/g, (_,$1,$2,$3) => $1+'~'.repeat($2.length)+$3);
txt = '==Hello==';
//inline function
console.log(
txt.replace(/(==)([^=]+)(==)/g, (_, g1, g2, g3) => g1 + '~'.repeat(g2.length) + g3)
);
The length attribute is being evaluated before the $2 substitution so replace() won't work. The function call suggested by Augustus should work, another approach would be using match() instead of replace().
Using match() without the /g, returns an array of match results which can be joined as you expect.
txt="==Hello==";
mat=txt.match(/(==)([^=]+)(==)/); // mat is now ["==Hello==","==","Hello","=="]
txt=mat[1]+Array(mat[2].length+1).join("~")+mat[3]; // txt is now "==~~~~~=="
You excluded the leading/trailing character from the middle expression, but if you want more flexibility you could use this and handle anything bracketed by the leading/trailing literals.
mat=txt.match(/(^==)(.+)(==$)/)
A working sample uses the following fragment:
var processed = original.replace(/(==)([^=]+)(==)/g, function(all, before, gone, after){
return before+Array(gone.length+1).join('~')+after;
});
The problem in your code was that you always measured the length of "$2" (always a string with two characters). By having the function you can measure the length of the matched part. See the documentation on replace for further examples.

Categories