Need to test JS 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 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)

Related

Javascript to extract certain string from data [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 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])

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

Javascript regular exp not working correctly [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 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

Replace in comma followed by double quotes in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Can anyone tell me how to replace comma followed by double quotes(",) with double quotes(") in java script
Actually I am getting the string as ",4,34,26,23"
but I want to remove the first comma in the string
also the same when it occurs at the last(,") as below
"4,34,23,54,"
Thanks in Advance
Rakesh
You can use regular expressions like this
var data = ",4,34,26,23,";
data = data.replace(/^,|,$/g, "");
console.log(data);
Output
4,34,26,23
If the double quotes are also part of the original string,
var data = "\",4,34,26,23,\"";
data = data.replace(/^",|,"$/g, "");
If you want to strip only the , and retain ", you can just put the double quotes as the second parameter to the replace, as suggested by #nnnnnn, like this
data = data.replace(/^,|,$/g, "\"");
data = data.replace(/^",|,"$/g, "\"");
var a = ",4,34,26,23";
var replaced=a.replace(',','');
alert(replaced);
Try this
var x = ',4,34,26,23';
x.replace(/^,|,$/g,'');
This removes any starting or ending commas :
",4,34,26,23,".replace(/^,|,$/g,"") // "4,34,26,23"
try this
var str = '",4,34,26,23"';
str = str.replace('",','"');

Regex that searches for a starting character, anything in between, then an ending character? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So basically, I have a hugeee list of values that I copied from my site and would like them as just plain text. I need to create a regex for Javascript that removes the unwanted stuff
Here is what the values look like before hand:
<option value="111122223333">Some text (45)</option>
<option value="345835385390">Some text (10)</option>
<option value="456727235764">Some text (50)</option>
Here is what they need to look like afterwards:
Some text
Some text
Some text
Is this possible with 1 regex, or will many be needed?
My thinking is that a regex looks for < anything in between, and then > could be used on both the opening and closing option tags. Then the regex could be slightly modified to look for opening ( and then closing ) to remove the counter numbers to the left of the 'Some text' string.
Still learing regex, so it would be great if someone could also add a small explanation to their answer so that I could have some understanding of it. Thanks.
You can probably simplify this if you can use a library like jQuery. In that case you can use the text() method of a jQuery object to get the inner text, then run a simple regex to remove the '(xx)' part:
var vals = $('option').map(function() {
return $(this).text().replace(/\s*\(\d*\)$/, '');
});
// vals => ["some text", "some text", "some text"]
here's a fiddle: http://jsfiddle.net/jhummel/U46pH/
if you can't use a library I think you are looking for a regex like:
/<[^>]+>([^\(]+)\(\d*\)<[^>]+>/g
edit
You asked for a regex explanation, let's look at it part by part
/ = start the regex
< = find a '<' character
[^>]+ = find any character that is not a '>' one or more times
> = find a '>' character
( = start a group, anything in the parens will be saved for later
[^(]+ = find any character that is not a '(' one or more times - need to escape it with a backslash because the paren is a reserved character in regex
) = close the group
( = find a '(' char - need to escape it with a backslash again
\d* = find any numbers zero or more times
) = find a ')' character - escaped again
< = find a '<' character
[^>]+ = find any character that is note a '>' one or more times
> = find a '>' character
/ = end the regex
g = regex flag. Means find all the matches don't stop after the first match
If that's all you hope to accomplish then you can use something like:
(>)(.+)(<)
and then grab the second group out of the match.
EDIT: The parentheses are used to denote groups.

Categories