check for character in var using javascript [duplicate] - javascript

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

Related

RegEx doesn´t work with Replace JavaScript Method

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

How can I match everything not in a character set with regex and jQuery?

I'm trying to exclude everything except [a-z] [A-Z] [0-9] and [~!#$].
if( $("#name").val().test(/[^a-zA-Z0-9~!#$]/)) {
alert("Disallowed character used.");
return false;
}
I thought test would return true if it finds a match and that because I included the caret symbol it should match everything that is not in my expression.
However input such as this works: jAcK%%$21#x
When it shouldn't work because it has symbols I'm trying to disallow.
Where have I gone wrong?
Thanks
Use match instead of test, since test is function of RegExp instead of String
var hasBadInput = !!"jAcK%%$21#x".match(/[^a-zA-Z0-9~!#$]/) //true
Or reverse the position
(/[^a-zA-Z0-9~!#$]/).test("jAcK%%$21#x") //returns true
Regexp.prototype.test() should be called on the regex.
var $name = $("#name");
$name.on("keyup", function(e) {
if(/[^a-zA-Z0-9~!#$]/.test($name.val())) {
console.log("Nope");
return false;
} else {
console.log("Good");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="name" >

Selecting all characters in string between nth number and nth number Regex

I am trying to use regex in a jQuery function to select and mask all characters in a string with an'x' except the first 4 and last 4 characters. The string can be any length. I can successfully mask the last 4 digits and first 4 digits separately but I don't really understand regex well enough to select the nth character in a string to the nth character and mask them. If anybody can help it would be very grateful - I have spent many hours trawling around forums and trying to write my own regex but to no avail.
Thanks
My current function looks like this:
<input type="text" class="read-only-mask" title="" value="1233434343434456789012" name="" id=""readonly />
<script>
$(document).ready(function() {
$('.read-only-mask').val(function(_,val) {
return val.replace(/.(?=.{4})/g, 'x');
});
});
</script>
This would show 1233434343434456789012 as xxxxxxxxxxxxxxxxxx9012
I need it to show as 1233xxxxxxxxxxxxxx9012 but the string could be any length so 123343434343 would need to show as 1233****4343 etc
you are far better off using a simpler approach. Save your self some time and headache and use the KISS method.
var maxMaskLength = 10;
var minMaskLength = 4;
$(document).ready(function() {
$('.read-only-mask').val(function(_, val) {
var valSplit = val.split("");
for (i = minMaskLength; i < maxMaskLength; i++)
valSplit[i] = 'x';
return valSplit.join("");
});
});
I would prefer to do it like this
var str = "1233434343434456789012",
res = Array.prototype.map.call(str, (e,i) => i > 4 && i < 9 ? "X" : e).join("");
console.log(res);
var str = "1233434343434456789012",
res = Array.prototype.map.call(str, (e,i,a) => i < a.length-4 ? "X" : e).join("");
console.log(res);
whichever best fits your application.
I would use this way:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="read-only-mask" title="" value="1233434343434456789012" name="" id=""readonly />
<script>
$(document).ready(function() {
$('.read-only-mask').val(function(_, val) {
val = val.split("");
for (i = 4; i < val.length; i++)
val[i] = 'x';
return val.join("");
});
});
</script>
For the above input, it shows 1233xxxxxxxxxxxxxxxxxx. If that's what you need?
You really dont need regex for this, all you're doing is 3 substrings
string start to the mask start (1)
mask start to mask end (2)
mask end to string end. (3)
You then form the string back together by concatenating (1) above, the mask char to the length of (2) and finally (3).
var input = "1234567890";
var output = input.substring(0,4) + (Array(3).join('*')) + input.substring(6,10)
console.log(output)
You can use capturing parentheses:
"111122222333".replace( /(.{4})(.{5})(.*)/, '$1xxxxx$3');
1111 will be $1, replaced by itself.
22222 will be $2, replaced by xxxxx.
333 will be $3, replaced by itself.

Javascript check if string contains only certain character

I want to return true if a given string has only a certain character but any number of occurrences of that character.Examples:
// checking for 's'
'ssssss' -> true
'sss s' -> false
'so' -> false
Check this
<div class="container">
<form action="javascript:;" method="post" class="form-inline" id="form">
<input type="text" id="message" class="input-medium" placeholder="Message" value="Hello, world!" />
<button type="button" class="btn" data-action="insert">Show</button>
</form>
</div>
JavaScript
var onloading = (function () {
$('body').on('click', ':button', function () {
var a = document.getElementById("message").value;
var hasS = new RegExp("^[s\s]+$").test(a);
alert(hasS);
});
}());
Example http://jsfiddle.net/kXLv5/40/
Just check if anything other than space and "s" is there and invert the boolean
var look = "s";
if(!new RegExp("[^\s" + look + "]").test(str)){
// valid
}
or check if they're the only one which are present with the usage of character class and anchors ^ and $
var look = "s";
if(new RegExp("^[\s" + look + "]$").test(str)){
// valid
}
Do it with sssssnake
'sss'.split('s').some(s => s) === true
'sssnake'.split('s').some(s => s) === false
first, convert the string into an array using split,
const letters ='string'.split('')
then, use the Set data structure and pass the array as an argument to the constructer. Set will only have unique values.
const unique = new Set(letters)
this unique will have only the unique characters, so, when you pass sss then this will have only a single s.
finally, if the unique array contains only one element, then we can say this string only contains the same letter.
if (unique.size === 1) { // the string contains only the same letters
Your function should look like this,
function isIdentile(string) {
const letters = string.split('');
const unique = new Set(letters)
return unique.size === 1 ? true: false;
}
Use a RegEx:
const allOne = str => /^(.)\1*$/.test(str)
console.log(allOne(prompt("input")))
Explanation of the RegEx:
^(.)\1*$ full RegEx
^ start of line
(.) any character, stored in group 1
\1* repeat group 1 zero or more times
$ end of line
Using Set + Array for this, additionally checking the "" empty string edge case:
const hasOnlyGivenCharType = (str, char) => {
const chars = Array.from(new Set(str))
return !chars.some(c => c !== char) && !!chars.length
}
console.log(hasOnlyGivenCharType('ssssss', 's')) // -> true
console.log(hasOnlyGivenCharType('sss s', 's')) // -> false
console.log(hasOnlyGivenCharType('so', 's')) // -> false
console.log(hasOnlyGivenCharType('', 's')) // -> false

Determine if string has any characters that aren't in a list of characters and if so, which characters don't match?

I'm working on a simple password validator and wondering if its possible in Regex or... anything besides individually checking for each character.
Basically if the user types in something like "aaaaaaaaa1aaaaa", I want to let the user know that the character "1" is not allowed (This is a super simple example).
I'm trying to avoid something like
if(value.indexOf('#') {}
if(value.indexOf('#') {}
if(value.indexOf('\') {}
Maybe something like:
if(/[^A-Za-z0-9]/.exec(value) {}
Any help?
If you just want to check if the string is valid, you can use RegExp.test() - this is more efficient that exec() as it will return true when it finds the first occurrence:
var value = "abc$de%f";
// checks if value contains any invalid character
if(/[^A-Za-z0-9]/.test(value)) {
alert('invalid');
}
If you want to pick out which characters are invalid you need to use String.match():
var value = "abc$de%f";
var invalidChars = value.match(/[^A-Za-z0-9]/g);
alert('The following characters are invalid: ' + invalidChars.join(''));
Although a simple loop can do the job, here's another approach using a lesser known Array.prototype.some method. From MDN's description of some:
The some() method tests whether some element in the array passes the test implemented by the provided function.
The advantage over looping is that it'll stop going through the array as soon as the test is positive, avoiding breaks.
var invalidChars = ['#', '#', '\\'];
var input = "test#";
function contains(e) {
return input.indexOf(e) > -1;
}
console.log(invalidChars.some(contains)); // true
I'd suggest:
function isValid (val) {
// a simple regular expression to express that the string must be, from start (^)
// to end ($) a sequence of one or more letters, a-z ([a-z]+), of upper-, or lower-,
// case (i):
var valid = /^[a-z]+$/i;
// returning a Boolean (true/false) of whether the passed-string matches the
// regular expression:
return valid.test(val);
}
console.log(isValid ('abcdef') ); // true
console.log(isValid ('abc1def') ); // false
Otherwise, to show the characters that are found in the string and not allowed:
function isValid(val) {
// caching the valid characters ([a-z]), which can be present multiple times in
// the string (g), and upper or lower case (i):
var valid = /[a-z]/gi;
// if replacing the valid characters with zero-length strings reduces the string to
// a length of zero (the assessment is true), then no invalid characters could
// be present and we return true; otherwise, if the evaluation is false
// we replace the valid characters by zero-length strings, then split the string
// between characters (split('')) to form an array and return that array:
return val.replace(valid, '').length === 0 ? true : val.replace(valid, '').split('');
}
console.log(isValid('abcdef')); // true
console.log(isValid('abc1de#f')); // ["1", "#"]
References:
JavaScript conditional operator (assessment ? ifTrue : ifFalse).
JavaScript Regular Expressions.
String.prototype.replace().
String.prototype.split().
RegExp.prototype.test().
If I understand what you are asking you could do the following:
function getInvalidChars() {
var badChars = {
'#' : true,
'/' : true,
'<' : true,
'>' : true
}
var invalidChars = [];
for (var i=0,x = inputString.length; i < x; i++) {
if (badChars[inputString[i]]) invalidChars.push(inputString[i]);
}
return invalidChars;
}
var inputString = 'im/b#d:strin>';
var badCharactersInString = getInvalidChars(inputString);
if (badCharactersInString.length) {
document.write("bad characters in string: " + badCharactersInString.join(','));
}

Categories

Resources