Remove characters from a string that are not firstname/surname characters - javascript

Please see the code below:
#HostListener('paste', ['$event'])
onPaste(event) {
var test = event.clipboardData.getData('text');
var removedNumbers = test.replace(/[0-9]/g, '');
}
Numbers are removed from the pasted text. It is a surname field, so should also exclude characters like {[}] etc.
How can I remove characters that are not valid for a name? I have read lots of simlar questions today like this one: how do i block or restrict special characters from input fields with jquery?. However, I have not found an answer to my specific question.

[^ ] matches anything(including space) that is not enclosed in the brackets, so you could place all characters you don't want to be removed inside the bracket. Note, however, that you have to escape special characters if they are part of the match. Also note that
you can specify a range of characters by using a hyphen, but if the
hyphen appears as the first or last character enclosed in the square
brackets it is taken as a literal hyphen to be included in the
character set as a normal character.
const regex = /[^a-z,' -]/gi;
console.log("Conan O'Brien".replace(regex, ''));
You may also use Unicode character ranges for non-English names, for example
for Chines 4e00 to 9fa5,
for most of Latin 0061 to 007A & 00DF to 00F6 & 00F8 to 01BF & 01C4 to 024F
for Geʽez 1200 to 135A
const regexLatin = /[^\u0061-\u007A\u00DF-\u00F6\u00F8-\u01BF\u01C4-\u024F ]/gui;
const regexChina = /[^\u4e00-\u9fa5 ]/gui;
const regexGeez = /[^\u1200-\u137F ]/gui;
console.log("Björk Guðmundsdóttir".replace(regexLatin, ''));
console.log("陳港生".replace(regexChina, ''));
console.log("ምኒልክ".replace(regexGeez, ''));
However, this is not an exhaustive list, you may refer to the List_of_Unicode_characters to make adjustments for your specific need.
Trying to match all names from 'all' languages could be very hard. The good news, however, is that Unicode_Property_Escapes are part of the ECMAScript 2020 Specification( currently on draft stage ) which will simplify the process a lot.
For example to match for Latin characters, you would use: /\p{Script=Latin}/u,
and to match for letters from 'all' languages, you would use: /\p{Letter}/gu or the short form /\p{L}/gu

Try this.
Vanilla Javascript
document.addEventListener("paste", event => {
event.preventDefault();
let clipboardData = event.clipboardData.getData("Text");
clipboardData = clipboardData.replace(/[0-9_!¡?÷?¿/\\+=##$%\ˆ&*(){}|~<>;:[\]]/g, "");
let allowedPasteTarget = ['textarea', 'text']
if (allowedPasteTarget.includes(document.activeElement.type)) {
let prevText = document.activeElement.value;
document.activeElement.value = prevText + clipboardData;
}
});
//To handle the copy button, [Optional]
document
.getElementById("copy-text")
.addEventListener("click", function(e) {
e.preventDefault();
document.getElementById("text-to-copy").select();
var copied;
try {
copied = document.execCommand("copy");
} catch (ex) {
copied = false;
}
if (copied) {
document.getElementById("copied-text").style.display = "block";
}
});
<div>
<input type="text" id="text-to-copy" placeholder="Enter text" />
<button id="copy-text">Copy</button>
<span id="copied-text" style="display: none;">Copied!</span>
</div>
<div>
<textarea name="paste-area" id="paste-area" cols="30" rows="10" placeholder="Paste it here"></textarea>
</div>
Angular
#HostListener('paste', ['$event'])
onPaste(event) {
var test = event.clipboardData.getData('text');
var removedNumbers = test.replace(/[0-9_!¡?÷?¿/\\+=##$%\ˆ&*(){}|~<>;:[\]]/g, '');
let allowedPasteTarget = ['textarea', 'text']
if (allowedPasteTaeget.includes(document.activeElement.type)) {
let prevText = document.activeElement.value;
document.activeElement.value = prevText + clipboardData;
}
}

Related

regex to replace non numeric

I want to replace all my non numeric characters with an empty string. I found this solution
I am trying to replace the value of an input element on change. But when I use above, it is not replacing until I press a number.
Each non-digit I type stays until I type a digit
Ex: 2aaaaa will not be replaced. But as soon as 2aaaa3 is typed it will replace all the a's and it becomes 23
Is this the normal behaviour? How can I achieve my requirement.
component.ts
mobileChanged = () => {
this.mobile = this.mobile.replace(/\D/g,'');
};
angular component.html
<input type="text" [(ngModel)]="mobile" (ngModelChange)="mobileChanged()">
You can use keyup from jQuery or onkeyup from Javascript.
$("document").ready(function() {
$("input").keyup(function() {
let v = this.value.replace(/\D/g, '');
this.value = v;
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="" />
Yes, it's the usual behaviour for ngModelChange but seems you need onkeyup event here to replace Non-digits. Something like-
function mobileChanged() {
var txtinput = document.getElementById("fname");
var x = txtinput.value.replace(/\D/g,'');
txtinput.value = x;
}
<input id ="fname" type='text' onkeyup="mobileChanged()">
See if you still have confusion: https://stackoverflow.com/a/46403258/1138192

compare Two field if the field is in the content of other field using javascript after submit button clicked

Hi I am not a javascript expert thats why I will really appreciate any advice
I have a textfield named try where in I will input something
ex:
try value is
87
then I have another textfield named field11
field11 has a value of
777-a98;87-bx23;000-t88;245-k7
I wanted to compare try and field11 if try is found in the content of field 11 it will set the textfield named msg to 87-bx23 matched
msg value will be
87-bx23 matched
my code is like this but its not giving the desired output I know my comparison is wrong it just I dont know how
<script>
$(document).ready( function(){
$('#submit').click(function() {
if (document.getElementById('try').value != document.getElementById('field11').value)
{
alert('dont match!');
$("#msg").val ("dont match!");
}
else if (document.getElementById('try').value == document.getElementById('field11').value) {
}alert(document.getElementById('try').value + " exists");
$("#msg").val(document.getElementById('try').value + " exists");
});
});
</script>
I also try this but if I input 77 it saying it exist even not
<div id="requirement #2">
<button type="button" id="button2" onclick="StringSearch()">Search</button>
</div>
<script>
function StringSearch() {
var SearchTerm = document.getElementById('try').value;
var TextSearch = document.getElementById('field11').value;
if (SearchTerm.length > 0 && TextSearch.indexOf(SearchTerm) > -1) {
alert("Patient Exists");
} else {
alert("Patient Does not exist click add if you want to add the patient");
$("#msg").val(document.getElementById('try').value + " exists");
$("#t1").val("1");
}
}
</script>
document.getElementById('field11').value.match(new RegExp("(" + "87" + "-[a-z0-9]+);"))[1])
The Generated Regex when try value = 87:
/(87-[a-z0-9]+);/
So what is this monstrosity? We generate a Regex Expression, that looks for the try value followed by a dash, and one or more characters from a-z or 1-9, followed by a semicolon. String.match() is used to determine an array of matches, the array[1] is the first capture group (the part of the RegEx between the brackets), which is in this case 87-bx23
I have tried to rewrite your code to store variables for the elements and use a Regexp to do the search for the value:
<script>
$(document).ready( function(){
var tryElem = document.getElementById('try');
var field1 = document.getElementById('field11');
$('#submit').click(function() {
var regex = new Regexp(tryelem +'[^;]*');
var match = regex.exec(field.value);
if (match)
{
alert(match + " exists");
$("#mag").val(match + " exists");
}
else
{
alert('dont match!');
$("#msg").val ("dont match!");
}
});
});
</script>
The code does more or less the same as yours, except for the regex:
tryelem +'[^;]*'
It builds a regular expression form the the value of tryElem and then it searches forward and matches up to the first semi colon (zero or more characters).
Now the match will contain: '87-bx23'.
You can try this:
<input type="text" id="try"/>
<input type="text" id="field11" value="777-a98;87-bx23;000-t88;245-k7"/>
<input type="text" id="msg"/>
<input type="button" id="submit"/>
And js:
$(function(){
$("#submit").click(function(){
var Try=$("#try").val(),
f11=$("#field11").val(),
msg=$("#msg");
//but if you want search in number part only (before dash sign), uncomment line below and comment next line.
//var r=((";"+f11+";").match(new RegExp(";([^;-]*"+Try+".*?-.+?);"))||[])[1];
var r=((";"+f11+";").match(new RegExp(";([^;]*"+Try+"[^;]*);"))||[])[1];
msg.val(r||"don't match!!");
});
});
You can check or change both of them online

How to check if a string contain a list if characters which are not in english

I want to valid textbox text. the textbox is for a phone number so, of course, letters and anything other the number I used different kinds of code
ex
$(document).ready(function () {
$("#sub").click(function () {
var regex = /[$%^&*()_+[]{}<>?]אבגדהוזחטיכךלמםנןסעפצקרשת \"/
var bleangth = $('.bphone').val().length;
var eleangth = $('.ephone').val().leangth;
var cbphone = $('.bphone').val();
var cephone = $('.ephone').val();
if (bleangth < 3 || eleangth < 7) {
$('#bad').removeClass("error");
$('#short').addClass("error");
}
else
if (regex.test(cbphone) || regex.test(cephone)) {
$('#short').removeClass("error");
$('#bad').addClass("error");
}
else {
$('#bad').removeClass("error");
$('#short').removeClass("error");
//$('h3').removeClass("snerror")
}
alert( "end " + regex.test(cephone) +" start " + regex.test(cbphone));
});
As you see I entered letters from different language but for some reason the code can't "read" it and return true is there a way maybe to get string split it to array and then use it? or different code or something I need to add/ download
Thank you in advance
You can make regular expression with unicode value
var regex = /^[\u05d0-\u05ea]|[$%^&*()_+{}<>\]\[?]$/
Example
$(document).ready(function(){
var regex = /^[\u05d0-\u05ea]|[$%^&*()_+{}<>\]\[?]$/
$("#buttonCheck").click(function(){
alert(regex.test($("#text").val()));
});
});
Example Link
If requirement is for only numbers to be input you should be able to use NOT operator ! operator with RegExp /\D/ ; e.g.; !/\D/.test(/*input*/) where true would be result if input is a digit, false if input is not a digit.
An approach using HTML5 <input> element with pattern attribute set to \d+, required attribute; <label> element, CSS :focus, :invalid , adjacent siblings selector +
input + label {
display:none;
}
input:focus:invalid + label {
display:block;
color:red;
}
<input type="text"
pattern="\d+"
placeholder="Please input digits 0-9"
required /><label>Invalid input. Please input digits 0-9</label>

How do I allow the user to only input a string?

function EnterCandidates() {
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
names = document.querySelectorAll('label[for^=V][id^=L_V]');
Array.prototype.forEach.call(names, function(label, index) {
if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
label.textContent = candidateNameInputs[index].value;
}
});
}
I have this code which gets the users input and changes the label with it but i want to add some code which only allows the user to enter letters of the alphabet. How would I go about this using this code?
If you are using modern browsers then user html5 validation -
<input type="text" name="name" class="field" pattern="[a-zA-Z ]+" />
It accepts a-z and A-Z plus space
listen to keyDown event and match with this regex:
/[a-zA-Z]+/
if you're targeting modern browsers only, you can try this:
<input type="text" pattern="[a-zA-Z]" title="Only letters" />
you can't avoid that the user types non alphabetic characters. But you can:
- control the input fields (onkeydown) and check if there are some characters you don't want Stackoverflow - force input to only alpha-letters
- do the same before the
label.textContent = candidateNameInputs[index].value;
line and filter/replace the characters you don't want
var val = document.getElementById('id').value;
if (!val.match(/^[a-zA-Z]+$/))
{
alert('Only alphabets are allowed');
return false;
}
full script
function EnterCandidates() {
console.log('woo');
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
names = document.querySelectorAll('label[for^=V][id^=L_V]');
Array.prototype.forEach.call(names, function (label, index) {
if (!candidateNameInputs[index].value.match(/^[a-zA-Z]+$/))
{
alert('Only alphabets are allowed');
}
else
{
if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
label.textContent = candidateNameInputs[index].value;
}
}
});
}
Here is one way to do it using Javascript.
http://jsfiddle.net/q60gm0ra/
var input = document.getElementById('alpha');
input.addEventListener('keypress',function(e) {
var str = String.fromCharCode(e.charCode);
if (!(/[A-Z]|\s/i).test(str)) {
e.preventDefault();
}
});

Limiting input to a set of characters while also displaying those characters

I have seen in a few "username" fields where you type in a username, and below it, in something like a span, it will append it to a url. A lot like what is happening as I type this in StackOverflow at the bottom.
I would like to show only allowed characters from a list, ignore any input of characters not in that list.
I am really new to JS. In this case, I am using Jquery, and have a sort of works with some parts, and other parts I do not, or I have not gotten there yet.
Desire:
Input form field accepts only characters from a list, others are ignored.
Get the new key as entered, and append it to an element.
Here is the mess I have so far:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#cart-name').keyup(function(e) {
var entered = $('#cart-name').val();
entered = entered.toUpperCase();
var allowed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
// fromCharCode always returns uppercase?
var entered_char = String.fromCharCode(e.which);
console.log('You entered: ' + entered_char);
var pos = allowed.indexOf(entered_char);
console.log('position is: ' + pos);
if (pos <= 0) {
console.log('does not contain');
} else {
console.log('contains');
}
$('#live').text(entered);
console.log(entered);
});
});
</script>
In the html I have:
<input type="text" name="cart_name" value="" id="cart-name" autocomplete="off" />
<br />
http://example.com/
<span id="live"></span>
<br />
Why not use a regular exprsession to replace non alphanumeric characters?
entered = entered.replace(/[^a-zA-Z 0-9]+/g,'');
Looking at your comments, you have some confusion over the different Key events:
keyup (and keydown) tell you which physical key has been pressed, while keypress will tell you which character has been typed - which is why you're always getting uppercase letters from fromCharCode.
I'm using something like this to sort out urls:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#cart-name').keypress(function(e) {
var entered = $('#cart-name').val();
// Regular Express to perform match on all alphanumeric characters,
// and - and _
var matchPattern = /[\w/_/-]/g;
var entered_char = String.fromCharCode(e.which);
console.log('You entered: ' + entered_char);
if (entered_char.match(matchPattern)) {
$('#live').text(entered + entered_char);
}
else if (enteredKey == " ") {
// Replace spaces with hyphens for SEO
$('#live').text(entered + "-");
}
});
});
</script>
Should see you right.

Categories

Resources