RegEx doesn´t work with Replace JavaScript Method - javascript

I need some help with Regular Expression, the problem is that I need apply the regex with Replace method in JavaScript. I saw a few post here in Stackoverflow but any regex doesn't works, I don't why.
I need that the user only can type in the input the following data:
100
100.2
100.23
Note: only number, it could be with one or two decimals maximum. Don't allow another symbols, and of course one comma.
I have been reading about it, and I used a few regex generator to see the match, so I made this one:
/^[a-zA-Z]+(\.[a-zA-Z]{0,2})?$/
I got a little bit confused at the beginning because I used in the replace method:
elementOne.addEventListener("input", function(event) {
this.value = this.value.replace(/^[a-zA-Z]+(\.[a-zA-Z]{0,2})?$/, '');
});
And right now I read the process like: if I type a letter from a to z,the method will replace to space ''. but the rest doesn't works in the method but works in the generator for example.
Here is an example, you will see in the first input my regex vs Sven.hig regex:
const elementOne = document.getElementById('elementOne');
const elementTwo = document.getElementById('elementTwo');
elementOne.addEventListener("input", function(event) {
this.value = this.value.replace(/^[a-zA-Z]+(\.[a-zA-Z]{0,2})?$/, '');
});
elementTwo.addEventListener("input", function(event) {
this.value = this.value.replace(/^\d+[,]?\d{0,2}/, '');
});
<p>Element One (My RegEx)</p>
<input id="elementOne" type="text" />
<p>Element Two (Stack RegEx)</p>
<input id="elementTwo" type="text" />
Also as a CodePen

Your regex is to match words not numbers you should replace [a-zA-Z]by [0-9] and the \. by \,
so your regex should look like this /^[0-9]+(\,[0-9]{0,2})?/
alternatively you could shorten the pattern /^\d+[,]?\d{0,2}/gm
here is code snippet to prevent user from entering words or any number that doesn't match the pattern
const elementTwo = document.getElementById('elementTwo');
var flag=false
elementTwo.addEventListener("input", function(event) {
pattern=/^\d+[,]?\d{0,2}$/
if (pattern.test(this.value)){
flag=true
l=this.value
if(flag&&this.value.length>1)
return this.value
else flag=false
}
else if(!pattern.test(this.value)&&flag==true){
return this.value=l
}
else if(!pattern.test(this.value)&&flag==false){
return this.value=""
}
});
<p>Element Two (Stack RegEx)</p>
<input id="elementTwo" type="text" />

It looks like you're confusing a few things:
Replacing invalid characters in a string
Defining a validation pattern
Preventing entry of text
If your goal is to validate that your string has the correct format, you'd define a regular expression like:
const validFormat = /^\d+(,\d{0,2})?$/;
console.log(validFormat.test('99')); // true
console.log(validFormat.test('100,23')); // true
console.log(validFormat.test('X00,2E')); // false
console.log(validFormat.test('%#&SJ&#UJ')); // false
If your goal is to remove invalid characters (non-digits, non commas), you can define a regular expression for those invalid characters, but that's not the same thing as making sure your string now has a valid format. RegExp isn't able to do anything like that:
const invalidChars = /[^\d,]/g;
const sanitized = someString.replace(invalidChars, '');
If you want to prevent typing characters, you're better off adding a keydown event handler to your input and prevent the default behavior for invalid keys.
const myInput = document.querySelector('#some-input');
myInput.addEventListener('keydown', ({ key, preventDefault }) => {
if (key !== ',' && (key < '0' || key > '9')) {
preventDefault();
}
});

Related

Javascript remove all characters by regex rules

Who can help me with the following
I create a rule with regex and I want remove all characters from the string if they not allowed.
I tried something by myself but I get not the result that I want
document.getElementById('item_price').onkeydown = function() {
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(this.value) == false ) {
this.value = this.value.replace(regex, "");
}
}
The characters that allowed are numbers and one komma.
Remove all letters, special characters and double kommas.
If the user types k12.40 the code must replace this string to 1240
Who can help me to the right direction?
This completely removes double occurrences of commas using regex, but keeps single ones.
// This should end up as 1,23243,09
let test = 'k1,23.2,,43d,0.9';
let replaced = test.replace(/([^(\d|,)]|,{2})/g, '')
console.log(replaced);
I don't believe there's an easy way to have a single Regex behave like you want. You can use a function to determine what to replace each character with, though:
// This should end up as 1232,4309 - allows one comma and any digits
let test = 'k12,3.2,,43,d0.9';
let foundComma = false;
let replaced = test.replace(/(,,)|[^\d]/g, function (item) {
if (item === ',' && !foundComma) {
foundComma = true;
return ',';
} else {
return '';
}
})
console.log(replaced);
This will loop through each non-digit. If its the first time a comma has appeared in this string, it will leave it. Otherwise, if it must be either another comma or a non-digit, and it will be replaced. It will also replace any double commas with nothing, even if it is the first set of commas - if you want it to be replaced with a single comma, you can remove the (,,) from the regex.

check for character in var using javascript [duplicate]

I have a page with a textbox where a user is supposed to enter a 24 character (letters and numbers, case insensitive) registration code. I used maxlength to limit the user to entering 24 characters.
The registration codes are typically given as groups of characters separated by dashes, but I would like for the user to enter the codes without the dashes.
How can I write my JavaScript code without jQuery to check that a given string that the user inputs does not contain dashes, or better yet, only contains alphanumeric characters?
To find "hello" in your_string
if (your_string.indexOf('hello') > -1)
{
alert("hello found inside your_string");
}
For the alpha numeric you can use a regular expression:
http://www.regular-expressions.info/javascript.html
Alpha Numeric Regular Expression
With ES6 MDN docs .includes()
"FooBar".includes("oo"); // true
"FooBar".includes("foo"); // false
"FooBar".includes("oo", 2); // false
E: Not suported by IE - instead you can use the Tilde opperator ~ (Bitwise NOT) with .indexOf()
~"FooBar".indexOf("oo"); // -2 -> true
~"FooBar".indexOf("foo"); // 0 -> false
~"FooBar".indexOf("oo", 2); // 0 -> false
Used with a number, the Tilde operator effective does
~N => -(N+1). Use it with double negation !! (Logical NOT) to convert the numbers in bools:
!!~"FooBar".indexOf("oo"); // true
!!~"FooBar".indexOf("foo"); // false
!!~"FooBar".indexOf("oo", 2); // false
If you have the text in variable foo:
if (! /^[a-zA-Z0-9]+$/.test(foo)) {
// Validation failed
}
This will test and make sure the user has entered at least one character, and has entered only alphanumeric characters.
check if string(word/sentence...) contains specific word/character
if ( "write something here".indexOf("write som") > -1 ) { alert( "found it" ); }
ES6 contains inbuilt method (includes) in String's prototype, which can be used to check if string contains another string or not.
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be'));
Following polyfill can be used to add this method in non-supported browsers. (Source)
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}
You're all thinking too hard. Just use a simple Regular Expression, it's your best friend.
var string1 = "Hi Stack Overflow. I like to eat pizza."
var string2 = "Damn, I fail."
var regex = /(pizza)/g // Insert whatever phrase or character you want to find
string1.test(regex); // => true
string2.test(regex); // => false
Learn Regex in 5 minutes?
Use a regular expression to accomplish this.
function isAlphanumeric( str ) {
return /^[0-9a-zA-Z]+$/.test(str);
}
If you're searching for character(s) in the start or at the end of the string, you can also use startsWith and endsWith
const country = "pakistan";
country.startsWith('p'); // true
country.endsWith('n'); // true
var inputString = "this is home";
var findme = "home";
if ( inputString.indexOf(findme) > -1 ) {
alert( "found it" );
} else {
alert( "not found" );
}
To test for alphanumeric characters only:
if (/^[0-9A-Za-z]+$/.test(yourString))
{
//there are only alphanumeric characters
}
else
{
//it contains other characters
}
The regex is testing for 1 or more (+) of the set of characters 0-9, A-Z, and a-z, starting with the beginning of input (^) and stopping with the end of input ($).
Kevins answer is correct but it requires a "magic" number as follows:
var containsChar = s.indexOf(somechar) !== -1;
In that case you need to know that -1 stands for not found.
I think that a bit better version would be:
var containsChar = s.indexOf(somechar) >= 0;
Try this:
if ('Hello, World!'.indexOf('orl') !== -1)
alert("The string 'Hello World' contains the substring 'orl'!");
else
alert("The string 'Hello World' does not contain the substring 'orl'!");
Here is an example: http://jsfiddle.net/oliverni/cb8xw/
String's search function is useful too. It searches for a character as well as a sub_string in a given string.
'apple'.search('pl') returns 2
'apple'.search('x') return -1
If you are reading data from the DOM such as a p or h1 tag, for example, you will want to use two native JavaScript functions, it is quiet easy but limited to es6, at least for the solution I am going to provide. I will search all p tags within the DOM, if the text contains a "T" the entire paragraph will be removed. I hope this little example helps someone out!
HTML
<p>Text you need to read one</p>
<p>Text you need to read two</p>
<p>Text you need to read three</p>
JS
let paras = document.querySelectorAll('p');
paras.forEach(p => {
if(p.textContent.includes('T')){
p.remove();
}
});
You can use string.includes(). Example:
var string = "lorem ipsum hello world";
var include = "world";
var a = document.getElementById("a");
if (string.includes(include)) {
alert("found '" + include + "' in your string");
a.innerHTML = "found '" + include + "' in your string";
}
<p id="a"></p>
Working perfectly.This exmple will help alot.
<script>
function check()
{
var val = frm1.uname.value;
//alert(val);
if (val.indexOf("#") > 0)
{
alert ("email");
document.getElementById('isEmail1').value = true;
//alert( document.getElementById('isEmail1').value);
}else {
alert("usernam");
document.getElementById('isEmail1').value = false;
//alert( document.getElementById('isEmail1').value);
}
}
</script>
<body>
<h1>My form </h1>
<form action="v1.0/user/login" method="post" id = "frm1">
<p>
UserName : <input type="text" id = "uname" name="username" />
</p>
<p>
Password : <input type="text" name="password" />
</p>
<p>
<input type="hidden" class="email" id = "isEmail1" name = "isEmail"/>
</p>
<input type="submit" id = "submit" value="Add User" onclick="return check();"/>
</form>
</body>
A sample regex pattern test you can use to find out if the string contains a character '#':
/(#[A-Za-z])\w+/.test(str_text)
Check if string is alphanumeric or alphanumeric + some allowed chars
The fastest alphanumeric method is likely as mentioned at: Best way to alphanumeric check in Javascript as it operates on number ranges directly.
Then, to allow a few other extra chars sanely we can just put them in a Set for fast lookup.
I believe that this implementation will deal with surrogate pairs correctly correctly.
#!/usr/bin/env node
const assert = require('assert');
const char_is_alphanumeric = function(c) {
let code = c.codePointAt(0);
return (
// 0-9
(code > 47 && code < 58) ||
// A-Z
(code > 64 && code < 91) ||
// a-z
(code > 96 && code < 123)
)
}
const is_alphanumeric = function (str) {
for (let c of str) {
if (!char_is_alphanumeric(c)) {
return false;
}
}
return true;
};
// Arbitrarily defined as alphanumeric or '-' or '_'.
const is_almost_alphanumeric = function (str) {
for (let c of str) {
if (
!char_is_alphanumeric(c) &&
!is_almost_alphanumeric.almost_chars.has(c)
) {
return false;
}
}
return true;
};
is_almost_alphanumeric.almost_chars = new Set(['-', '_']);
assert( is_alphanumeric('aB0'));
assert(!is_alphanumeric('aB0_-'));
assert(!is_alphanumeric('aB0_-*'));
assert(!is_alphanumeric('你好'));
assert( is_almost_alphanumeric('aB0'));
assert( is_almost_alphanumeric('aB0_-'));
assert(!is_almost_alphanumeric('aB0_-*'));
assert(!is_almost_alphanumeric('你好'));
GitHub upstream.
Tested in Node.js v10.15.1.
It's worked to me!
Attribute Contains Selector [name*=”value”]
This is the most generous of the jQuery attribute selectors that match against a value. It will select an element if the selector's string appears anywhere within the element's attribute value. Compare this selector with the Attribute Contains Word selector (e.g. [attr~="word"]), which is more appropriate in many cases.
source: Attribute Contains Selector [name*=”value”] => https://api.jquery.com/attribute-contains-selector/
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>attributeContains demo</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">
<script>
$( "input[name*='man']" ).val( "has man in it!" );
</script>
</body>
</html>
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// expected output: true
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// expected output: true
console.log(pets.includes('at'));
// expected output: false
know more
Demonstration: The include() method finds the “contains” character in whole string, it will return a true.
var string = "This is a tutsmake.com and this tutorial contains javascript include() method examples."
str.includes("contains");
//The output of this
true

How do i exclude certain characters from a given string?

I've made a html file with a text area and a button that should essentially filter a string that i submit the way i need it too.
tried using the functions includes,gsub and replace with several variation.
let filtered = []
document.querySelector('#filter').addEventListener('submit',function (e){
filtered = e.target.elements.text.value
if (filtered.includes('Hi')){
console.log(filtered)
const filteredEl = document.createElement('div')
filteredEl.textContent = filtered
document.querySelector('#filtered').appendChild(filteredEl)
}
e.preventDefault()
})
i need only A-Z characters and completely erase unwanted ones such as () etc.
if possible, without any spaces.
Welcome to regexp world
const onlyCapitalLetters = value.replace(/[^A-Z]/g, '');
You may want also small letters and spaces
const onlyText = value.replace(/[^A-Za-z ]/g, '');
You can even use regexp as pattern for inputs
<input type="text" pattern="[A-Za-z ]*" ...>
You can playaround with regexpes here
Use a regular expression to match and remove everything that isn't an alphabetical character via a negative character set:
document.querySelector('#filter').addEventListener('submit', function(e) {
const filteredText = e.target.elements.text.value
.replace(/[^a-z]+/gi, '');
if (filteredText.includes('Hi')) {
console.log(filteredText)
const filteredEl = document.createElement('div')
filteredEl.textContent = filteredText
document.querySelector('#filtered').appendChild(filteredEl)
}
e.preventDefault()
})
[^a-z] with the case-insensitive i flag will match everything other than alphabetical characters a to z.

Javascript Regular Expressions are not working; always returns false

I need to write a regular expression that will check that the strings matches the format 'ACT' followed by 6 digits eg. 'ACT123456'
Though it looks quite simple, none of my options work; the function always returns false.
I tried the following combinations:
Pure regexpression literals
var format = /^ACT\d{6}$/;
var format = /^ACT[0-9]{6}$/;
Or using RegExp object with double escaping (eg. \\d) and with single escaping (\d)
var format = new RegExp("^ACT\\d{6}$");
var format = new RegExp("^ACT[0-9]{6}$");
My function for testing is:
function testPattern(field, pattern) {
if (!pattern.test(field)) {
return false;}
else {
return true;
}}
var format = /^ACT\d{6}$/;
works fine but the string must be ACT123456 exactly with nothing preceding it or following it
eg 'ACT123456 ' fails
use
/ACT\d{6}/
to allow more tolerance or strip the whitespace from the string first
var testString = "ACT123456"; // string to test
// pattern as a regex literal
var pattern = /^ACT[0-9]{6}$/g;
console.log(testString.match(pattern)); // output: ["ACT123456"]
Thanks you all guys for answers and feedback!
After being stuck with regular expressions, I realized that my problem with that I am not using field.value in my function.
So, the problem is with the function that must be:
function testPattern(field, pattern) {
if (!pattern.test(field.value)) {
return false;}
else {
return true;
}}

Checking for invalid characters from an input with jQuerys

I have an input box where the a username is input'd but if invalid characters are input'd, I want it to error. The code below is what I'm using; What would i put in the "something" section?
var numbers = new RegExp("SOMETHING");
$(this).removeClass("active");
if(($(this).val() == "") || $(this).val().match(numbers))
{
$("#firstNameErrorMsg").html("First name can only contain letters. ");
}
else
{
$("#firstNameErrorMsg").html("OK");
}
Here are some patterns I wrote them long years ago:
patt['name'] = /^[a-z ,-]+$/i;
patt['username'] = /^[A-z0-9_-]+$/i;
patt['email'] = /^[a-z0-9]+(?:[\.-]?[a-z0-9]+)*#[a-z0-9]+([-]?[a-z0-9]+)*[\.-]?[a-z0-9]+([-]?[a-z0-9]+)*([\.-]?[a-z]{2,})*(\.[a-z]{2,5})+$/i;
patt['website'] = /^http(s)?:\/\/(www\.)?[a-z0-9]+([-]?[a-z0-9]+)*[\.-]?[a-z0-9]+([-]?[a-z0-9]+)*([\.-]?[a-z]{2,})*(\.[a-z]{2,5})+$/i;
patt['age'] = /^(?:([1][3-9]|[2-9][0-9]))$/i;
patt['subject'] = /[a-z0-9?!:;'&_\. ,-]+/i;
If you want to use them, you should check this condition:
if(($(this).val() == "") || ! $(this).val().match(patt['name'])){ // in case.
...
}
But if you want to check undesirable characters, it'll be a long pattern for username input.
Try this Regex
[A-Za-z]
This will match only lowercase and uppercase characters
Suggest you read a bit about regexes and experiment with them.
To get simply letters and nothing else, just do:
^[a-zA-Z]+$
That allows 1..n lowercase & uppercase letters to be found between start and end, nothing else. Sushanth's version will match partial pieces of the input, letting the user to use spaces, numbers, etc. elsewhere as long as there's one piece of of the input with a word in it.
This should be a full implementation of what you're trying to do:
var invalid = /[^A-Za-z]+/;
$(this).removeClass("active");
if($(this).val() == "" || invalid.test($(this).val()))
{
$("#firstNameErrorMsg").html("First name can only contain letters. ");
}
else
{
$("#firstNameErrorMsg").html("OK");
}
Sushanth is mostly correct, but you will need to match any number of letters, and it has to be from the start to the end only letters, so you should do something like this
var name = new RegExp('^[A-Za-z]+$');
$(this).removeClass('active');
if($(this).val().match(name)) {
$('#firstNameErrorMsg').html('OK');
} else {
$('#firstNameErrorMsg').html('First name can only contain letters.');
}
If you are looking for validating your users input , to only have letters , i would suggest using the char code, something like this :
add the keypress event on the input tag
for the event args passed, check the character code (Some browsers use keyCode, others use which)
function checkOnKeyDown(event){
if (event.KeyCode >= 65 && event.keyCode <=122)
{
//all ok here -- only upper/lowercase letters accepted
}
else
{
//wrong
}
}
Here is a list with all the keyCode to characters mapping ;) : http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Categories

Resources