How do i modify .replace to allow numbers, comma and dots [duplicate] - javascript

I have a string. I need to parse it, replacing any chars (except numbers (0 to 9),, and ..
How can I do it with javascript?
Tried with :
string.replace(/[a-zA-Z]*/, "");
but seems it doesnt works. Also, I need ANY chars, not only a-Z (also ?, /, white space, and so on, expect, as said, , and .

Use a negated character class
[^0-9,.]
and put in any character you don't want to be replaced, it will match all the others.
See it here on Regexr
You can optimize it by adding a quantifier +, so that it replaces a sequence of those characters at once and not each by each.
string.replace(/[^0-9,.]+/g, "");
As Felix Kling pointed out, its important to use the global option g to match on all occurrences of the pattern.
See it here on Regexr

string.replace(/[^\d,.]+/g, "");
should do.
[^\d.,] means "any character except digit, comma or period", a negated character class.
Use + instead of * or you'll have lots of empty matches replaced with empty strings.
Use /g so all instances are replaced.

Try to replace all chars except digits and . , and do the replace globally:
string.replace(/[^0-9\,\.]+/g, "");

Try This
Below code is prevent alpha key
onKeypress="return Custom(event,'[0-9]');"
function Custom(e, cPattern) {
var key = [e.keyCode || e.which];
var pattern = new String(cPattern);
var keychar = String.fromCharCode([e.keyCode || e.which]);
var pattern1 = new RegExp(pattern);
if ((key == null) || (key == 0) || (key == 8) ||
(key == 9) || (key == 13) || (key == 27)) {
return true;
}
else if (pattern1.test(keychar)) {
return true;
}
else {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
}

Related

hyphens in Regular Expressions/ javascript camelCase function

The Function should take a string as an argument and camel case it. I am having trouble with hyphens while using regex and string.replace() method.
camelCase('state-of-the-art') should return 'state-of-the-art'
camelCase("Don't worry kyoko") should return "dontWorryKyoko"
The following works for both cases, but I want to make it DRY, take out the hyphens if clause and include the hyphen case in .replace() and it's call-back.
function camelCase(phrase) {
let re = /[a-z]+/i;
let hyphens = /[-+]/g
if(typeof phrase !== 'string' || !phrase.match(re) || !phrase || phrase === null){
return "Please enter a valid string.";
} else if (phrase.match(hyphens)){
return phrase.toLocaleLowerCase();
}else{
return phrase.replace(/(?:^\w+|[A-Z]|\s+\w)/g, function(letter, index) {
return index == 0 ? letter.toLowerCase() : letter.toUpperCase();
}).replace(/\W+/g, '');
}
}
console.log(camelCase('state-of-the-art')) // 'state-of-the-art'
console.log(camelCase("Don't look back")) // dontLookBack
Can we make the hyphen case work without the hyphens if clause?
Also I feel like camelCase("don't lOOk_BaCK") should lowercase letters with index > 0 but it doesn't seem to be doing that in the console.
Anyone wanna help with this? Thanx
To cope with the hyphen issue you may consider - a part of alphanumeric class by using [\w-] or [^\w-] where appropriate.
To lowercase all non-first letters I suggest to match all words with (\S)(\S*) uppercasing $1 (where appropriate) and lowercasing $2:
function camelCase(phrase) {
return phrase.replace(/[^\w-]*(\S)(\S+)/g, function(_, first, rest, index) {
return (index ? first.toUpperCase() : first.toLowerCase())
+ rest.toLowerCase();
}).replace(/[^\w-]+/g, "");
}
console.log(camelCase("state-of-the-art"));
console.log(camelCase("-state-of-the-art"));
console.log(camelCase("Don't look back"));
console.log(camelCase("don't lOOk_BaCK"));
console.log(camelCase("???don't lOOk_BaCK"));
You can make the hyphens work by adding a negative lookahead assertion .replace(/(?!-)\W+/g, '');. This would tell it to replace all non-word characters, except a - dash character.
Regarding your lower-casing problem: your only criteria right now to decide the case is if it appears at the beginning of the string. Otherwise you're UPPER casing everything (including the upper case matches). This is also a pretty easy fix. Here's the whole thing:
function camelCase(phrase) {
let re = /[a-z]+/i;
if (typeof phrase !== 'string' || !phrase.match(re) || !phrase || phrase === null) {
return "Please enter a valid string.";
} else {
return phrase.replace(/(?:^\w+|(\s+)\w)|[A-Z]/g, function (letter, sp, index) {
console.log(letter, sp, index);
return (index == 0 || sp === undefined) ? letter.toLowerCase() : letter.toUpperCase();
}).replace(/(?!-)\W+/g, '');
}
}
Explanation of the changes:
change order of asssertions in phrase.replace regexp. We want a space-word combo to take precedence over a capitalized match.
add a capturing group to the space, so that we can know better if the capture follows a space
change the boolean expression: we want it to be lower case if:
it's the first character (index===0)
OR there isn't a space match (this would be an [A-Z] match, without a preceding space)
Also just as an aside, you don't appear to be camel-casing on a _ underscore character, only on spaces. Is this intentional? I've never seen a camel-case routine that didn't convert snake-case (underscore).

Javascript Regular Expression that diallows special characters

I have the below 3 function.
I cant seem to get the right regular expression
Please assist me
//Allow Alphanumeric,dot,dash,underscore but prevent special character and space
function Usernames(txtName) {
if (txtName.value != '' && txtName.value.match(/^[0-9a-zA-Z.-_]+$/) == null) {
txtName.value = txtName.value.replace(/[\W- ]/g, '');
}
}
//Allow Alphanumeric,dot,dash,underscore and space but prevent special characters
function Fullnames(txtName) {
if (txtName.value != '' && txtName.value.match(/^[a-zA-Z0-9. -_]+$/) == null) {
txtName.value = txtName.value.replace(/[\W-]/g, '');
}
}
//Allow Alphanumeric,dot,dash,underscore the "#" sign but prevent special character and space
function Email(txtName) {
if (txtName.value != '' && txtName.value.match(/^[a-zA-Z0-9.-_#]+$/) == null) {
txtName.value = txtName.value.replace(/[\W-]/g, '');
}
}
You don't write regular expressions to "prevent" something; they're not blacklists but whitelists. So, if someone is sending in a character that you don't want it's because your regex allowed them to. My guess as to your specific problem has to do with the .-_ part. In regex's, the X-Y means "everything from X to Y" so this would translate to "everything from . (ASCII 2E) to _ (ASCII 5F)" which ironically includes all uppercase and lowercase letters, the numbers 0 to 9, the /, the :, the ; and the # just to name a few. To avoid this, you should probably change this part to be: .\-_ as the slash will escape the dash. However, that'll still let your users make names like .Bob or -Larry and you probably don't want this so your regex should probably read:
/^[0-9a-zA-Z][0-9a-zA-Z.\-_]*$/
This will require the first character to be alphanumeric and any of the remainder to be alphanumeric, the ., the - or the _.
You'll also want to check that your value matches this reg-ex instead of not. I'm not sure what that entails in Javascript but my guess is that it's probably not value == null

How do I check for brackets in a specific place in the string?

I have this code and it needs to returns true or false based on the string you give it.
This is the only example on which it doesn't work. How can I check if brackets exist in a specific index of the string?
function telephoneCheck(str) {
var newStr = str.replace(/-/g,'').replace(/ /g,'').replace(/\(|\)/g,'');
var valid = true;
var re = /\([^()]*\)/g;
while (str.match(re))
str = str.replace(re, '');
if (str.match(/[()]/)){
valid = false;
}
if(newStr.length === 10 && valid === true && str.indexOf()){
return true;
}else if(newStr.length === 11 && str[0] != "-" && newStr[0] == 1 && valid === true){
return true;
}else{
return false;
}
}
telephoneCheck("(6505552368)");
Based on your code I think you might be looking for something like this:
'(6505552368)'.replace(/^\((\d+)\)$/, '$1');
The ^ and $ in the RegExp will match the start and the end of the string. The \d+ will match one or more numbers. The extra parentheses form a capture group that is then used in the replacement as $1.
You might be better off doing more work using RegExps rather than doing all that replacing but without knowing the exact requirements it's difficult to be more precise. I highly suggest learning more about RegExp syntax.
If you literally just want to know whether 'brackets exist in a specific index' then you can just use:
str.charAt(index) === '(';
To check if there are brackets at a specific index in the string:
/[()]/.test(str[index])
To check if there are any brackets in the string at all:
/[()]/.test(str)
If you want to test for a specific bracket type (e.g. opening but not closing) remove the other one (e.g. closing) from the regex.

Trouble with easy Coderbyte challenge counting x's and o's

I'm new to JavaScript and not sure why my code isn't working. I'm trying to return true if there are an equal amount of x's and o's, and return false if there are not. My code works for all inputs except "x" and "o". Any help is appreciated!
My code:
function ExOh(str) {
var x = str.match(/[^x$]/gi);
var o = str.match(/[^o$]/gi);
if (x.length == o.length) {
return true;
}
else {
return false;
}
}
Your regexps allow any characters other than x/y and $. You must have meant /x/gi and /o/gi.
function ExOh(str) {
var x = str.match(/x/gi) || "";
var o = str.match(/o/gi) || "";
if (x.length === o.length) {
return true;
}
else {
return false;
}
}
alert(ExOh("zzz"));
alert(ExOh("oozzzxx"));
Note that negated character classes like [^x] match all characters other than those inside the square brackets. $ inside them is treated as a literal dollar sign.
Typing a caret after the opening square bracket negates the character class. The result is that the character class matches any character that is not in the character class. Unlike the dot, negated character classes also match (invisible) line break characters. If you don't want a negated character class to match line breaks, you need to include the line break characters in the class. [^0-9\r\n] matches any character that is not a digit or a line break.
You need to set the value to something other than null if the str.match doesn't actually match something. You can't call length on null. Use the or operator to set the value to an empty string in your variable declaration.
function ExOh(str) {
var x = str.match(/[^x$]/gi) || '';
var o = str.match(/[^o$]/gi) || '';
if (x.length == o.length) {
return true;
}
else {
return false;
}
}
I hope this helps
Here's a solution for checking that the number of two characters is the same.
// How many 'x' characters occur in a string?
function numberOf(str, x) {
var matches = str.match(new RegExp(x, 'g'));
return matches ? matches.length : 0;
}
// Create a function to check if the number of x's and o's in
// a string are the same.
function same(x, o) {
return function(str) {
return numberOf(str, x) === numberOf(str, o);
};
}
var isSame = same('x', 'o');
isSame('xxooabc');
Remove ^ and $ from your regex , [^o$] match a single character not o or $. You just need to use /x/ and /o/ and flags ig, i for ignoring case and g for global match.
Typing a caret after the opening square bracket negates the character class. The result is that the character class matches any character that is not in the character class. Unlike the dot, negated character classes also match (invisible) line break characters. If you don't want a negated character class to match line breaks, you need to include the line break characters in the class. [^0-9\r\n] matches any character that is not a digit or a line break. ( Taken from http://www.regular-expressions.info/charclass.html )
Update : Add (!x && !o) and x && o in condition for avoiing error when zero matches are there. (!x && !o) for when both are not present.x && o will help only to check the condition x.length == o.length when both x and o are defined.
var div = document.getElementById('res');
function ExOh(str) {
var x = str.match(/x/gi);
var o = str.match(/o/gi);
if ((!x&&!o) || x && o && x.length == o.length) {
res.innerHTML = 'Same';
return true;
} else {
res.innerHTML = 'Not Same';
return false;
}
}
<input type=text oninput="ExOh(this.value)">
<div id=res></div>

How to modify a text inputbox so that it accepts only certain characters?

I've an input box in which I only want to allow 0-9, (, ), -, ., and (space) characters. After researching and picking up code from different tutorials, I managed to (I think) come up with the required regex pattern.
But it isn't working and always returning false even if the character typed is one from the above. The code that I've with me is as follows:
var regex = new RegExp("/[0-9.\(\)\b\ -]/", "gi");
if(regex.test(str)){
return true;
} else {
console.log('failed');
return false;
}
I'm having failed printed in the console every single time. What am I missing here?
EDIT: Demo (It seems to be working here)
EDIT2: JSFIDDLE
UPDATE:
I think my question is being misinterpreted here. I probably didn't do a good job at describing my use case. Well here it is then:
In my textbox, I only want to allow the above mentioned characters. So if a user types "23a" in the textbox, it should only allow "23" and "a" shouldn't be allowed to be typed
new RegExp() is superfluous here, just use regex literal notation (see note #2 below).
You want to anchor the expression to the beginning (^) and the end ($) of the string, to make sure it applies to the entire string. That's what you have tried to accomplish with g, but that is not what g does.
The i (case-insensitive) modifier is not necessary either, the pattern does not contain letters.
function isValidChar(str) {
return /^[0-9.() -]$/.test(str);
}
$(function(){
$('#p_zip').on('keypress', function (e) {
return isValidChar(String.fromCharCode(e.keyCode));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="p_zip">
Here is a version that works entirely without regex, comparing the keycode is enough.
function filterNumericKey(e) {
var c = e.keyCode;
return (c >= 48 && c <= 57) || // "0" .. "9"
c === 32 || // " "
c === 40 || // "("
c === 41 || // ")"
c === 45 || // "-"
c === 46; // "."
}
$(function(){
$('#p_zip').on('keypress', filterNumericKey);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="p_zip">
Notes
The following is an anti-pattern, in any language, not just JS:
if (booleanCondition) {
return true;
} else {
return false;
}
Just use return booleanCondition; directly instead.
If you want to use new RegExp() instead of a regex literal, you
must not use forward slashes to delimit your expression
must escape any backslashes, just like you would do in any other JavaScript string
Beware that both solutions will not check text that is pasted or dropped on the input element. You might want to write checks for that as well.
I managed to solve it. I was making a rookie mistake. I needed to return false on keypress event instead of keyup. And I was also taking the value of the textbox into account instead of the event object.
function isNumber(e) {
var theEvent = e || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
if (key.length == 0) return;
var regex = /^[0-9\.\b\(\) -]+$/;
if (!regex.test(key)) {
return false;
} else {
return true;
}
}

Categories