How do i exclude certain characters from a given string? - javascript

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.

Related

Javascript Regex - replacing characters based on regex rules

I am trying to remove illegal characters from a user input on a browser input field.
const myInput = '46432e66Sc'
var myPattern = new RegExp(/^[a-z][a-z0-9]*/);
var test = myPattern.test(myInput);
if (test === true) {
console.log('success',myInput)
} else {
console.log("fail",myInput.replace(???, ""))
}
I can test with the right regex and it works just fine. Now I am trying to remove the illegal characters. The rules are, only lower case alpha character in the first position. All remaining positions can only have lower case alpha and numbers 0-9. No spaces or special characters. I am not sure what pattern to use on the replace line.
Thanks for any help you can provide.
Brad
You could try the below code:
const myInput = '46432e66Sc'
var myPattern = new RegExp(/^[a-z][a-z0-9]*/);
var test = myPattern.test(myInput);
if (test === true) {
console.log('success',myInput)
} else {
console.log("fail",myInput.replace(/[^a-z0-9]/g, ""))
}
Replace is using the following regexp: /[^a-z0-9]/g. This matches all characters that are not lowercase or numeric.
You can validate your regexp and get help from cheatsheet on the following page: https://regexr.com/
You could handle this by first stripping off any leading characters which would cause the input to fail. Then do a second cleanup on the remaining characters:
var inputs = ['abc123', '46432e66Sc'];
inputs.forEach(i => console.log(i + " => " + i.replace(/^[^a-z]+/, "")
.replace(/[^a-z0-9]+/g, "")));
Note that after we have stripped off as many characters as necessary for the input to start with a lowercase, the replacement to remove non lowercase/non digits won't affect that first character, so we can just do a blanket replacement on the entire string.

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.

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

Insure that regex moves to the second OR element only if the first one doesn't exist

I'm trying to match a certain word on a string and only if it doesn't exist i want to match the another one using the OR | operator ....but the match is ignoring that... how can i insure that the behavior works :
const str = 'Soraka is an ambulance 911'
const regex = RegExp('('+'911'+'|'+'soraka'+')','i')
console.log(str.match(regex)[0]) // should get 911 instead
911 occurs late in the string, whereas Soraka occurs earlier, and the regex engine iterates character-by-character, so Soraka gets matched first, even though it's on the right-hand side of the alternation.
One option would be to match Soraka or 911 in captured lookaheads instead, and then with the regex match object, alternate between the two groups to get the one which is not undefined:
const check = (str) => {
const regex = /^(?=.*(911)|.*(Soraka))/;
const match = str.match(regex);
console.log(match[1] || match[2]);
};
check('Soraka is an ambulance 911');
check('foo 911');
check('foo Soraka');
You can use includes and find
You can pass the strings in the priority sequence, so as soon as find found any string in the original string it returns that strings back,
const str = 'Soraka is an ambulance 911'
const findStr = (...arg) => {
return [...arg].find(toCheck => str.includes(toCheck))
}
console.log(findStr("911", "Soraka"))
You can extend the findStr if you want your match to be case insensitive something like this
const str = 'Soraka is an ambulance 911'
const findStr = (...arg) => {
return [...arg].find(toCheck => str.toLowerCase().includes(toCheck.toLowerCase()))
}
console.log(findStr("Soraka", "911"))
If you want match to be whole word not the partial words than you can build dynamic regex and use it search value
const str = '911234 Soraka is an ambulance 911'
const findStr = (...arg) => {
return [...arg].find(toCheck =>{
let regex = new RegExp(`\\b${toCheck}\\b`,'i')
return regex.test(str)
})
}
console.log(findStr("911", "Soraka"))
Just use a greedy dot before a capturing group that matches 911 or Soraka:
/.*(911)|(Soraka)/
See the regex demo
The .* (or, if there are line breaks, use /.*(911)|(Soraka)/s in Chrome/Node, or /[^]*(911)|(Soraka)/ to support legacy EMCMScript versions) will ensure the regex index advances to the rightmost position when matching 911 or Soraka.
JS demo (borrowed from #CertainPerformance's answer):
const check = (str) => {
const regex = /.*(911)|(Soraka)/;
const match = str.match(regex) || ["","NO MATCH","NO MATCH"];
console.log(match[1] || match[2]);
};
check('Soraka is an ambulance 911');
check('Ambulance 911, Soraka');
check('foo 911');
check('foo Soraka');
check('foo oops!');

Test for specific number of words to match, with a known separator with Regex in Js

i'm trying to check wether a string matches a set of values and they are seperated by a ; It needs to have ; as a separator.
I go this new RegExp(/\b(Segunda|Terça|Quarta|Quinta|Sexta|Sábado|Domingo)\b/, 'gi').test(str)
If i pass:
'Segunda;Terça', true.
'Segundaaa', false.
'Segunda;Terçaa', true.. Why is it true? how can i avoid this?
Thanks in advance.
[EDIT] code:
const WEEK_DAYS_GROUP_REGEX = /\b(Segunda|Terça|Quarta|Quinta|Sexta|Sábado|Domingo)\b/;
const res = new RegExp(WEEK_DAYS_GROUP_REGEX, 'i').test('Segunda;Terçaa');
console.log(res) // gives true
The /\b(Segunda|Terça|Quarta|Quinta|Sexta|Sábado|Domingo)\b/ pattern with gi modifiers matches any of the alternatives as a whole word, it does not guarantee that the whole string consists of these values only, let alone the ; delimiter.
You may use
^(<ALTERNATIONS>)(?:;(<ALTERNATIONS>))*$
See the pattern demo.
In JS, you do not need to use that long pattern, you may build the pattern dynamically:
const strs = ["Segunda;Terça", "Segundaaa", "Segunda;Terçaa"];
const vals = "Segunda|Terça|Quarta|Quinta|Sexta|Sábado|Domingo";
let rx = new RegExp("^(?:" + vals + ")(?:;(?:" + vals + "))*$", "i");
console.log(rx);
for (let s of strs) {
console.log(s,"=>",rx.test(s));
}
Note that the non-capturing groups (?:...) are preferred when there is no need extracting submatches, group values.

Categories

Resources