How to convert string with concatenation to real string in javascript? - javascript

I have a string which looks like this on a page response (saved as autoResponse):
... hexMD5('\262' + '****' + '\155\135\053\325\374\315\264\062\232\354\242\205\217\034\154\005'); ...
In order to capture this, I use:
var hex = autoResponse.split('hexMD5(')[1].split(')')[0];
This now gives me this string:
'\262' + '****' + '\155\135\053\325\374\315\264\062\232\354\242\205\217\034\154\005'
If I put this directly into the hexMD5() method, it thinks that the ', + symbols and white space are apart of the secret.
I tried to use replace() to remove them like so:
while(hex.split("'").length !== 1) hex = hex.replace("'", "");
while(hex.split("+").length !== 1) hex = hex.replace("+", "");
while(hex.split(" ").length !== 1) hex = hex.replace(" ", "");
However, when I then do hexMD5(hex) it gives me an incorrect hex. Is there anyway I can convert the hex to a string where it combines the strings together as if I was hardcoding it like
hexMD5('\262' + '****' + '\155\135\053\325\374\315\264\062\232\354\242\205\217\034\154\005');
any help would be appreciated.

You can use a single, much simpler RegExp for this:
hex = hex.replace(/' ?\+ ?'/g, '');
That says "replace all single-quotes, followed by possibly a space, then a plus, then possibly another space, followed by another single quote" and replaces those matches with nothing, thus removing them. (You need the \ before the + because + is a special character in RegExes that needs to be escaped.)

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.

Regular expression when reading files javascript

I have a situation where I have 3 font files and I read its content in order to find mathes with font name. But the thing is that font names are Wingdings, Wingdings 2, Wingdings 3. And when I have Wingdings font name it matches all 3 files, but I need file that exactly is associated with font name, not all 3 of them. I tried to find it using indexOf method, but it didn't help. The only rational way is to use regular expression, but cannot think of a right one. One more thing need to be mentioned is that I have to pass a parameter into that regExp, something like
var regExp = new RegExp('\\^' + fontName + '$\\', 'g');
if (currentFileContent.search(regExp) !== -1) {...}
Any help will be greatly appreciated.
It seems you try to use regex delimiters in a RegExp constructor. You only need /.../ in the literal notation.
Note you need not escape the start and end of string anchors, they lose their special meaning in the regex then. \\ matches a single \, but it cannot be matched after end of string ($).
Also, you can use RegExp#test() function to check if the string matches the pattern (note no g modifier can be used with it):
var regExp = RegExp('^' + fontName + '$');
if (regExp.test(currentFileContent)) { ... }
If font names contain special characters, use escapeRegExp function from MDN:
function escapeRegExp(string){
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
And then
var regExp = RegExp('^' + escapeRegExp(fontName) + '$');
And the final note: if the font names appear inside a larger string, and you need to match Windings but not Windings3, use
var regExp = RegExp('\\b' + escapeRegExp(fontName) + '\\b');
The \b is a word boundary.
UPDATE
To make sure you only match a font name that is not followed by a whitespace (if any) and a digit, use a (?!\\s*\\d) lookahead when declaring a RegExp:
var fontName = "Wingding";
var contents = "Font name: Wingding, the other file: Font name: Wingding 2. And so forth. ";
var rExp = RegExp(fontName + '(?!\\s*\\d)');
if (rExp.test(contents)) {
document.write(fontName + " was found in '<i>" + contents + "</i>'.");
}

JS - Remove all characters before/after a string (and keep that string)?

I've seen several results for removing characters after a specific character - my question is how would I do that with a string?
Basically, this applies to any given string of data, but let's take a URL: stackoverflow.com/question
With given string, and in JS, I'd like to remove everything after ".com", assign ".com" to a variable, and assign the text before ".com" to a separate variable.
So, end result: var x = "stackoverlow" var y = ".com"
What I've done so far:
1) Using a combination of split, substring, etc. I can get it to remove pieces, but not without removing part of the ".com" string. I'm pretty sure I can do what I want to do with substring and split, I think I'm just implementing it incorrectly.
2) I'm using indexOf to find the string ".com" within the full string
Any tips? I haven't posted my actual code because it's become so garbled with all the different things I've tried (I can go ahead and do so if necessary).
Thanks!
You should really look into Regular Expressions.
Here is some code that can get what you are trying to do:
var s = 'stackoverflow.com/question';
var re = /(.+)(\.com)(.+)/;
var result = s.match(re);
if (result && result.length >= 3) {
var x = result[1], //"stackoverlow"
y = result[2]; //".com"
console.log('x: ' + x);
console.log('y: ' + y);
}
Use regular expressions.
"stackoverflow.com".match(/(.+)(\.com)/)
results in
["stackoverflow.com", "stackoverflow", ".com"]
(Why would you want to assign .com to a variable, though?
"stackoverflow.com".split(/\b(?=\.)/) => ["stackoverflow", ".com"]
Or,
"stackoverflow.com/question".split(/\b(?=\.)|(?=\/)/)
=> ["stackoverflow", ".com", "/question"]

A simple javascript regex backreference

I have the following string that I am attempting to match:
REQS_HOME->31
The following Javascript code is attempting to match this:
pathRegExPattern = '(' + docTypeHome + ')' + '(->)' + '(\d+)';
parsedResult = pathCookieValue.match(pathRegExPattern);
cookieToDelete = docType + '_ScrollPos_' + $3;
alert(parsedResult); // output - null
Assume the following:
docTypeHome = "REQS_HOME"
pathCookieValue = "REQS_HOME->31"
Firstly, I am not calling my match function properly. And secondly, how do I access the value where I am attempting to match the digit values using the backreference operator?
I need to extract the value 31.
Your digit-matching part needs to double-up on the backslashes:
pathRegExPattern = '(' + docTypeHome + ')' + '(->)' + '(\\d+)';
When you build up a regular expression from string parts, the string syntax itself will "eat" a backslash. Thus, the regex you were winding up with was just d+, without the backslash.
The "31" (or whatever the number ends up being) will be in parsedResult[3]. Note that it'll be a string, so if you need it to be a number you'll want to convert it first, via the Number constructor, or parseInt(), or whatever.

Javascript RegEx non-capturing prefix

I am trying to do some string replacement with RegEx in Javascript. The scenario is a single line string containing long comma-delimited list of numbers, in which duplicates are possible.
An example string is: 272,2725,2726,272,2727,297,272 (The end may or may not end in a comma)
In this example, I am trying to match each occurrence of the whole number 272. (3 matches expected)
The example regex I'm trying to use is: (?:^|,)272(?=$|,)
The problem I am having is that the second and third matches are including the leading comma, which I do not want. I am confused because I thought (?:^|,) would match, but not capture. Can someone shed light on this for me? An interesting bit is that the trailing comma is excluded from the result, which is what I want.
For what it is worth, if I were using C# there is syntax for prefix matching that does what I want: (?<=^|,)
However, it appears to be unsupported in JavaScript.
Lastly, I know I could workaround it using string splitting, array manipulation and rejoining, but I want to learn.
Use word boundaries instead:
\b272\b
ensures that only 272 matches, but not 2725.
(?:...) matches and doesn't capture - but whatever it matches will be part of the overall match.
A lookaround assertion like (?=...) is different: It only checks if it is possible (or impossible) to match the enclosed regex at the current point, but it doesn't add to the overall match.
Here is a way to create a JavaScript look behind that has worked in all cases I needed.
This is an example. One can do many more complex and flexible things.
The main point here is that in some cases,
it is possible to create a RegExp non-capturing prefix
(look behind) construct in JavaScript .
This example is designed to extract all fields that are surrounded by braces '{...}'.
The braces are not returned with the field.
This is just an example to show the idea at work not necessarily a prelude to an application.
function testGetSingleRepeatedCharacterInBraces()
{
var leadingHtmlSpaces = ' ' ;
// The '(?:\b|\B(?={))' acts as a prefix non-capturing group.
// That is, this works (?:\b|\B(?=WhateverYouLike))
var regex = /(?:\b|\B(?={))(([0-9a-zA-Z_])\2{4})(?=})/g ;
var string = '' ;
string = 'Message has no fields' ;
document.write( 'String => "' + string
+ '"<br>' + leadingHtmlSpaces + 'fields => '
+ getMatchingFields( string, regex )
+ '<br>' ) ;
string = '{LLLLL}Message {11111}{22222} {ffffff}abc def{EEEEE} {_____} {4444} {666666} {55555}' ;
document.write( 'String => "' + string
+ '"<br>' + leadingHtmlSpaces + 'fields => '
+ getMatchingFields( string, regex )
+ '<br>' ) ;
} ;
function getMatchingFields( stringToSearch, regex )
{
var matches = stringToSearch.match( regex ) ;
return matches ? matches : [] ;
} ;
Output:
String => "Message has no fields"
fields =>
String => "{LLLLL}Message {11111}{22222} {ffffff}abc def{EEEEE} {_____} {4444} {666666} {55555}"
fields => LLLLL,11111,22222,EEEEE,_____,55555

Categories