Why regex doesn't work some times in javascript? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Hello I'm using regex to validate inputs, The idea is that the user cannot type some characters based on regex. I tested with 2 regex, but te first doesn't work.
Even I test on that page: https://regexr.com/
and both works fine, but in the code they don't.
Would you please helpme? Thanks.
I need a regex that letme type range betwen 0 and 180
the desired behaviour:
function regex1(str) {
var splitStr = str.split("");
var filterArray = splitStr.filter(function(val) {
// Test the string against the regular expression
// and test for no match (whole thing is preceeded by !)
return !/^([0-9]|[1-9][0-9]|1[0-7][0-9]|180)$/g.test(val);
});
return filterArray;
}
function regex2(str) {
var splitStr = str.split("");
var filterArray = splitStr.filter(function(val) {
// Test the string against the regular expression
// and test for no match (whole thing is preceeded by !)
return !/[^1-3]+/g.test(val);
});
return filterArray;
}
console.log(regex1("180"));
console.log(regex2("3"));

Your problem lies on two fronts:
Your var splitStr = str.split(""); line is splitting the string down to individual characters, which means you are never testing '180', but '1', '8', and '0' separately
RegEx is a poor tool to validate numerical range
You should really really really reconsider using regex for this purpose, and instead should parse the input into a number and test it, unless there's some other reason that you need to do it this way. One reason to parse and test instead is that there may be edge cases that your expression doesn't cover, even though they may be valid.
If, for some reason, you absolutely must use regex, you need to test the string(s?) as a whole, rather than char by char, just by using the same RegExp.prototype.test() function like you already were:
function regex1(str) {
return /^([0-9]|[1-9][0-9]|1[0-7][0-9]|180)$/g.test(str);
}
var tests = ['0', '1', '120', '180', '181'];
for (var str of tests)
console.log(`${str}:`, regex1(str));
As an example of an alternate solution:
If you're using HTML <input>s for form input, then they already have a mechanism for setting a max (and min) numerical input. Trying to submit with invalid input will prevent form submission:
<form>
<input type="number" max="180" placeholder="0 - 180">
<input type="Submit">
</form>

Related

Restore a string that has randomly inserted characters [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I would like to clean this string How52363262362366are9you?, or any similar string that the user inputs, using wherever character he wants.
This was my first approach :
function buildstring(str){
var reg =/[0-9]/g;
let newStr = str.replace(reg, '');
return newStr;
}
console.log(buildstring('How52363262362366are9you?'));
This way I'm only deleting the digits. I can make the regex even better by adding some non alphanumeric characters, but let's keep it simple.
This function returns Howareyou?. Now I want to separate the words with a space to reconstruct the sentence.
My first idea was using split(''), but of course didn't work...
How to solve this? Is there any way to make that a word starts at point a and ends in point c?
Just change your regex a bit so that it matches grouped numerical characters, and replace each group with a space.
function buildstring(str){
var reg =/[0-9]+/g;
let newStr = str.replace(reg, ' ')
return newStr
}
buildstring('How52363262362366are9you?')
there are several approaches.
You could consider it a case for Functional Programming (since there's a flow of transformations).
Something like this:
function buildstring(str){
return str
.split('')
.filter((character) => !'0123456789'.includes(character))
.join('');
}
console.log(buildstring('How52363262362366are9you?'));
If you use split(' ') (or even break on \s to consider tabs and newlines), you'll have „words” (with interpunction).
By breaking up the code into smaller functions, you can compose them.
For example, the .filter() could be a stripnumerals function.
This way, you can compose the transformations as you please.

Find and replace # mentions using Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to parse strings to find and replace # mentions.
Here is a sample string:
Hi #jordan123 and #jordan have a good day
I want to find and replace #jordan with #jordananderson without modifying #jordan123
I used this regex to find a list of all of the mentions in the string:
let string = 'Hi #jordan123 and #jordan have a good day'
let result = string.match(/\B\#\w\w+\b/g);
that returns:
['#jordan123', '#jordan']
But I can't figure out how to continue and complete the replacement.
Valid characters for the username are alphanumeric and always start with the # symbol.
So it also needs to work for strings like this:
Hi #jordan123 and #jordan!! have a good day
And this
Hi #jordan123! and !#jordan/|:!! have a good day
My goal is to write a function like this:
replaceUsername(string, oldUsername, newUsername)
If I understand your question correctly, you need \b, which matches a word boundary:
The regex: #jordan\b will match:
Hi #jordan123 and #jordan!! have a good day
Hi #jordan123! and !#jordan/|:!! have a good day
To build this regex, just build it like a string; don't forget to sanitize the input if it's from the user.
var reg = new RegExp("#" + toReplace + "\\b")
In general if you have one string of a found value, and a larger string with many values, including the found value, you can use methods such as split, replace, indexOf and substring etc to replace it
The problem here is how to replace only the string that doesn't have other things after it
To do this we can first look for indexOf the intended search string, add the length of the string, then check if the character after it doesn't match a certain set of characters, in which case we set the original string to the substring of the original up until the intended index, then plus the new string, then plus the substring of the original string starting from the length of the search string, to the end. And if the character after the search string DOES match the standard set of characters, do nothing
So let's try to make a function that does that
function replaceSpecial(original, search, other, charList) {
var index= original.indexOf(search)
if(index > -1) {
var charAfter = original [index + search.length]
if (!charList.includes(charAfter)) {
return original. substring (0, index) + other + original. substring (index+ search.length)
} else return original
} else return original
}
Then to use it with our example
var main ="Hi #jordan123 and #jordan!! have a good day"
var replaced = replaceSpecial (main, "#jordan", "#JordanAnderson", [0,1,2,3,4,5,6,7,8,9])

Regex to evaluate a list of 6 digit numbers separated by commas [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have an input field that I would like users to put in a list of numbers that are 6 digits long. the list the users input will have variable lengths.
Pass
123456, 123457, 156545, 546541, 546541
Pass
123456, 123457
Pass
546541
Fail
12345, 155154
Fail
154s54, 159475, 153456
Fail
154s544, 159475, 153456
The regEx you are looking for is /^\d{6}$/, which matches a 6 digit number and only 6 digit number.
var cases = [
'123456, 123457, 156545, 546541, 546541',
'123456, 123457',
'546541',
'12345, 155154',
'154s54, 159475',
'154s544, 159475, 153456'
];
//Break up numbers in string into array the check each token
//against the regex. If all tokens passes the test, then it
//returns true, else false.
t = cases.map(c => c.split(', ')
.reduce((p, n) => p && !!n.match(/^\d{6}$/), true));
for (let i=0; i < cases.length;i++)
console.log('case:', cases[i], t[i]?'pass':'fail');
Assuming that you are not looking to capture the individual numbers, but just want to validate the input, the following regex should do:
^(\d{6},\s*)*\d{6}$
Breakdown of the regex:
^ beginning of the string
(\d{6},\s*)* zero or more occurrences of a 6-digit number, followed by a comma and optional whitespace
\d{6} a 6-digit number (this is the last and possibly the only one)
$ end of the string
Note that the expression enclosed within parentheses is a capture group. To avoid capture and make it stricter the expression would be written as:
^(?:\d{6},\s*)*\d{6}$
Note the ?: after the first parenthesis. It means match the expression but do not capture it.

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)

How to check open or close parentheses in string before comma? [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
I have condition for text field that each string should have open and close parentheses before ending with comma ?
Example :
valid text values- stack(2),flow(2),over(4),temp(0)
Invalid - stack(2),flow,over(4),temp(0)
So , each string should have () parentheses before end with comma.How to check this condition, Please advise.
Count number of () before each come with RegExp \([^,]+\), it should be equal to number of comas+1
Here is working solution with test cases: http://jsfiddle.net/c8t26/1/
function testCases(str){
return (
str.match(new RegExp("\\([^,]+\\)","g")).length == str.split(",").length
);
}
Here is my solution, split the string with comma, then filter it with a regexp then compare with original size.
Demo
var a = 'stack(2),flow(2),over,temp ';
var arr = a.split(',');
var temp = arr;
arr = arr.filter(function(el){
var reg = new RegExp(/\(\d+\)$/);
el = el.trim();
return !!reg.test(el)
});
if(arr.length !== temp.length){
alert(temp.length - arr.length + ' wrong');
}
Filter support
Use a for loop to pass through each character of the string. Use a flag eg. openParentheses where you increase the count for each ( and decreases for each ) if you end up with anything other than 0 it is not valid, if you end up with anything less than 0 it is not valid and in your case if you cant have more than one parenthesis open then if your variable is greater than 1 in any iteration through the loop it is not valid. If you need to look for the coma too, just when you find a ) check for [i+1] to see if it is a comma. Watch out if it is the end of the string so you don't get an out of bounds error. Either make a special case (if) or add some dummy character to the end which is not ).

Categories