Javascript replace using key mappings and regex [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am attempting to create a function that encodes special characters in a url. I looked into the npm package: urlencode but it doesn't encode all characters for some reason (such as parenthesis). I start by replacing the percent symbol so there is no interference with the rest of the code replacements. I made a mapObj array to feed into a regex and for some reason all of these characters are not getting replaced. The parenthesis and the periods especially. Any idea why?
const replaceSpecialChars = function (str) {
str = str.replace('%', '%25')
var mapObj = {
"&":"%26",
"`":"%60",
"-":"%2D",
"|":"%7C",
".":"%2E",
"(":"%28",
")":"%29"
};
var re = new RegExp(Object.keys(mapObj).map(key => key.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')).join('|'));
str = str.replace(re, function(matched){
return mapObj[matched];
});
}

I believe you have overcomplicated it a little bit, single String#replace is enough.
var mapObj = {
"&": "%26",
"`": "%60",
"-": "%2D",
"|": "%7C",
".": "%2E",
"(": "%28",
")": "%29"
};
const replaceSpecialChars = (str) =>
str.replace(/./g, (m) => mapObj[m] ?? m);
console.log(replaceSpecialChars('&_-_(_)_.'));

Related

How to escape the double forwardslash in regex (javascript) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
How to replace the specific string only using one replace instead of two?
const formattedUrl = url.replace('flashget://', '').replace('&abc','')
What I have tried: (Not Working)
const formattedUrl = url.replace(/flashget:\/\/ | &abc/g, '').replace('&abc','')
Example
Input Url: flashget://W0ZMQVNIR0VUXWh0dHA6Ly93d3cuZm9yZWNlLm5ldC93aW43LnJhcltGTEFTSEdFVF0=&abc
Formatted Url: W0ZMQVNIR0VUXWh0dHA6Ly93d3cuZm9yZWNlLm5ldC93aW43LnJhcltGTEFTSEdFVF0=
Take out the spaces around the |
This is my attempt:
https://regex101.com/r/eFO7Eh/2
Search Regex:
flashget:\/\/(.*)\&.*$
Replace term:
$1
Just pay attention to the fact that this is a different logic and requires handling capture groups.
remove the space before and after the or |. it will work.
let url = "flashget://W0ZMQVNIR0VUXWh0dHA6Ly93d3cuZm9yZWNlLm5ldC93aW43LnJhcltGTEFTSEdFVF0=&abc"
const formattedUrl = url.replace(/flashget:\/\/|&abc/g, '');
console.log(formattedUrl);

How do I remove brackets and bracketed contents? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I tried .replace(/ *\[[^)]*\] */g, ""); and it works for instances where there's only a pair of brackets
"[Dialog4]Hello, this is Mike"
but doesn't work for
"[Dialog4]Hello, this is Mike[Dialog5]"
because it just removes entire thing
The result should be
"Hello, this is Mike"
use not greedy mode in regex:
\[.*?\]
here is a tester: https://regex101.com/r/NyireC/1
You can use
\[[^\]]*\]
let str = "[Dialog4]Hello, this is Mike[Dialog5]"
let replaced = str.replace(/\[[^\]]*\]/g,"")
console.log(replaced)
Your regex is almost there.
You don't need the space+* at the start and end, because you only want to replace the square brackets and their contents, not anything before/after it.
In the negated character class, you are negating ), where you should be negating ] instead. This is possibly a typo.
With these modifications, the regex becomes:
\[[^\]]*\]
Demo
Perhaps a bit sloppy, but you could use the regex /\[(?<=\[)[^\]]*(?=\])]/g.
This makes use of both a positive lookbehind and positive lookahead, on the [ and ] characters respectively.
const string = "[Dialog4]Hello, this is Mike[Dialog5]";
const regex = /\[(?<=\[)[^\]]*(?=\])]/g;
const output = string.replace(regex, "");
console.log(output);

How to test pattern regexpr in javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
In javascript I have a string containing a pattern '/^\d{7,15}$/' and I would test string str1
How can I use this string '/^\d{7,15}$/' ???
var re = '/^\d{7,15}$/';
var str1 = '12345678'; //should match!
// none of the below methods is working to me
var m1 = str1.match(re);
console.log(m1); //null
var regex1 = new RegExp(re);
var t1 = regex1.test(str1);
console.log(t1); //false
You need to escape your backslash \ in your string literal:
var re = '^\\d{7,15}$';
var str1 = '12345678'; //should match!
var regex1 = new RegExp(re);
var t1 = regex1.test(str1);
console.log(t1);
I also removed the slashes / around your expression, as they are not required. As Paulpro mentions in the comments, if you do not control the input string, you can strip them out with str1.slice(1, -1).

Need to test JS regex [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
When I type in my input the text appears on image. I want to make the code work like that:
When user types character that is recognized by regex then place it on image else just throw some error or do not let it type at all in the input field.
This is the regex: [A-Z0-9a-z&,.-/()#*+!?"':; -]
I'm trying to achieve it like this:
$("#firstText").keyup(function () {
var value = $(this).val().toUpperCase();
var regex = "[A-Z0-9a-z&,.-/()#*+!?"':; -]";
if(regex.test(value))
{
$(".zetin16").text(value);
} else {
alert('this is bad');
}
});
But I get this error: Uncaught SyntaxError: Invalid or unexpected token
In this line: var regex = "[A-Z0-9a-z&,.-/()#*+!?"':; -]";
Thanks in advance for any help.
UPDATE
The regex working fine now. Now I want to prevent typing characters in input when regex doesnt match the character. This is my code currently:
$("#firstText").keyup(function(e) {
var value = $(this).val().toUpperCase();
var regex = new RegExp(/[A-Z0-9a-z&,.-/()#*+!?"':; -]/);
if (regex.test(value)) {
$(".zetin16").text(value);
} else {
e.preventDefault();
return false;
}
});
With regex, use the forward slash as delimiter. If a forward slash occurs as a literal inside the regex itself, escape it:
var regex = /[A-Z0-9a-z&,.-\/()#*+!?"':; -]/;
Reference: JavaScript regex replace - escaping slashes
(The problem with the original string was that it contained a double quote, and was delimited using double quotes at the same time).
The exact error you're seeing is because you are defining the variable as a double quoted string, with an unescaped double quote in it.
It shouldn't be a string anyway. It should be a regular expression like this.
var regex = /[A-Z0-9a-z&,.-/()#*+!?"':; -]/;
try using this pattern for using regular expression
var regex = "['A-Z0-9a-z&,.-/()#*+!?':; -]";
var reg =new RegExp(regex)
var val ="asss"
reg.test(val)

Issue With Replacing RegExp Terms In String [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
var testString = "This string has a bad word in it to test";
function findBadWords(string) {
var badWord = /\bbad\b | \bword\b | \btest\b/gi
var isBadWord = string.match(badWord);
if (isBadWord) {
newString = string.replace(badWord," *** ");
}
document.write(newString);
}
findBadWords(testString);
So I'm practicing with RegExp's currently and I have run into a problem I don't understand. In the code above, I have set a RegExp to find "bad words" in a string. From what I can tell, I have set it to find the word "bad", "word", and "test" as long as there is a word boundary before and after the word. The issue I'm having is that "word" isn't being replaced. If I put a non-badWord before "word" it gets replaced, but not otherwise. I have tried taking off some of the word boundaries or adding some non-word boundaries with no luck. Would anyone mind explaining why this code is working the way that it is and how I could fix it?
Thanks!
Also, I know using document.write is a poor choice but it's only for testing I swear!
The issue here is the \b alongside the " " empty space character. If you remove the spaces from your regex it works well.
var testString = "This string has a bad word in it to test";
function findBadWords(string) {
var badWord = /\bbad\b|\bword\b|\btest\b/gi
var isBadWord = string.match(badWord);
if (isBadWord) {
newString = string.replace(badWord," *** ");
}
document.write(newString);
}
findBadWords(testString);

Categories