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);
Related
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('&_-_(_)_.'));
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 need to find a regex to extract first occurrence of a string from a data.
For example my data is like :
SFASDŞŞVMA SAD SADAS MYABCD12345678911TY ISIADABCD12345678911SAD
I need to extract ABCD123456789 from this data.
I need to find first occurrence of string always starts with ABCD and has total length of 13.
How can I achieve this with using regex?
I tried regex /^ABCD(\w{9})$/gm which didn't work for me.
You can use /ABCD\w{9}/g with match() to get the result from first index:
var str = "SFASDŞŞVMA SAD SADAS MYABCD12345678911TY ISIADABCD12345678911SAD"
console.log(str.match(/ABCD\w{9}/g)[0])
The pattern that you tried ^ABCD(\w{9})$ does not match because you use anchors ^ and $ to assert the start and the end of the string.
Note that if you want a full match only, you don't need a capturing group (\w{9})
You can omit those anchors, and if you want a single match from the string you can also omit the /g global flag and the /m multiline flag.
ABCD\w{9}
Regex demo
const regex = /ABCD\w{9}/;
const str = `SFASDŞŞVMA SAD SADAS MYABCD12345678911TY ISIADABCD12345678911SAD`;
console.log(str.match(regex)[0])
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);
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)
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 8 years ago.
Improve this question
I wrote this JS code for validating the password must not contain the (!) char.
fiddle : http://jsfiddle.net/sr8xm/
var pattern = /[A-Za-z0-9.#&#_-]{6,20}/;
$("#pwd").blur(function(){
pwd = $(this).val();
if(!pattern.test(pwd)){
alert('Please enter valid new password.');
return false;
}
});
but this returns true if someone type ! char after 6 chars ??
any idea what going wrong in this.
Anchor your regex:
var pattern = /^[A-Za-z0-9.#&#_-]{6,20}$ /;
You could also reduce it to:
var pattern = /^[\w.#&#-]{6,20}$/;
/[A-Za-z0-9.#&#_-]{6,20}/ can match the middle part of the password string. For example it matches "!mypassword!" and return true. You'd use ^ (matches the beginning of the string) and $ (matches the end of the string) like /^[A-Za-z0-9.#&#_-]{6,20}$/.
If you want to restrict your chosen characters, you can use another expression which will check presence of restricted characters. But anchoring regex is also quick solution for your prob
var pattern = /[A-Za-z0-9.#&#_-]{6,20}/g;
var restrictedChar =/[!]+/g; // Add more character here which u want to restrict
var pwd = $("#pwd").val();
if(!pattern.test(pwd) || restrictedChar.test(pwd)){
alert('Please enter valid new password.');
return false;
}
Demo