I have a little code snippet where I use Regular Expressions to rip off punctuation, numbers etc from a string. I am getting undefined along with output of my ripped string. Can someone explain whats happening? Thanks
var regex = /[^a-zA-z\s\.]|_/gi;
function ripPunct(str) {
if ( str.match(regex) ) {
str = str.replace(regex).replace(/\s+/g, "");
}
return str;
}
console.log(ripPunct("*#£#__-=-=_+_devide-00000110490and586#multiply.edu"));
You should pass a replacement pattern to the first replace method, and also use A-Z, not A-z, in the pattern. Also, there is no point to check for a match before replacing, just use replace directly. Also, it seems the second chained replace is redundant as the first one already removes whitespace (it contains \s). Besides, the |_ alternative is also redundant since the [^a-zA-Z\s.] already matches an underscore as it is not part of the symbols specified by this character class.
var regex = /[^a-zA-Z\s.]/gi;
function ripPunct(str) {
return str.replace(regex, "");
}
console.log(ripPunct("*#£#__-=-=_+_devide-00000110490and586#multiply.edu"));
Related
I'm trying to create a function that removes all special characters (including periods) except apostrophes when they are naturally part of a word. The regex pattern I've made is supposed to remove anything that doesn't fit the schema of word either followed by an apostrophe ' and/or another word:
function removeSpecialCharacters(str) {
return str.toLowerCase().replace(/[^a-z?'?a-z ]/g, ``)
}
console.log(removeSpecialCharacters(`I'm a string.`))
console.log(removeSpecialCharacters(`I'm a string with random stuff.*/_- '`))
console.log(removeSpecialCharacters(`'''`))
As you can see from the snippet it works well except for removing the rogue apostrophes.
And if I add something like [\s'\s] or ['] to the pattern it breaks it completely. Why is it doing this and what am I missing here?
Alternate the pattern with '\B, which will match and remove apostrophes which are not followed by a word character, eg ab' or ab'#, while preserving strings like ab'c:
function removeSpecialCharacters(str) {
return str.toLowerCase().replace(/'\B|[^a-z'? ]/g, ``)
}
console.log(removeSpecialCharacters(`I'm a string.`))
console.log(removeSpecialCharacters(`I'm a string with random stuff.*/_- '`))
console.log(removeSpecialCharacters(`'''`))
(you can also remove the duplicated characters from the character set)
Not sure what went wrong with yours as I can't see what you attempted. However, I got this to work.
function removeSpecialCharacters(str) {
str = str.toLowerCase();
// reduce duplicate apostrophes to single
str = str.replace(/'+/g,`'`);
// get rid of wacky chars
str = str.replace(/[^a-z'\s]/g,'');
// replace dangling apostrophes
str = str.replace(/(^|\s)'(\s|$)/g, ``);
return str;
}
console.log(removeSpecialCharacters(`I'm a string.`))
console.log(removeSpecialCharacters(`I'm a string with random stuff.*/_- '`))
console.log(removeSpecialCharacters(`'''`))
console.log(removeSpecialCharacters(`regex 'til i die`))
Here's one very easy solution. To remove certain characteristics from a string, you can run a bunch of if-statements through a while loop. This allows you to chose exactly which symbols to remove.
while (increment < string.length)
{
if (string[increment] == "!")
}
delete "!";
}
increment += 1;
}
That's a simple rundown of what'll look like (not actual code) to give you a sense of what you're doing.
I'm trying to validate the value of an input text field with the following code:
function onBlurTexto(value) {
var regexNIT = "([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])";
regexCompilado = new RegExp(regexNIT);
if (!(regexCompilado.test(value))) {
alert("Wrong character in text :(");
return false;
} else {
return true;
}
}
But when i enter this text:
!65a
the function returns true (as you can see, the "!" character does not exist in the regular expression)
I'm not an expert in regular expressions, so i think i am missing something in the building of this reg.exp.
How can i put this regular expression to work?
Thanks in advance.
EDIT
i am so sorry ... i should remove the references to the variable "regexpValidar" before posting the issue. I modified the sample. Thanks #TecBrat
You should provide the start (^) and end ($) flags to your regex. Now you are matching 65a since you have alternate sets.
This should work /^([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])+$/g
Demo: https://regex101.com/r/zo2MpN/3
RegExp.test looks for a match in the string, it doesn't verify that the whole string matches the regex. In order to do the latter, you need to add start and end anchors to your regex (i.e. '^' at the start and '$' at the end, so you have "^your regex here$").
I also just noticed that your regex is currently matching only one character. You probably want to add a '+' after the parens so that it matches one or more:
"^([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])+$"
This is wrong. the variable you use doesn't has anything. Try this instead.
var regexCompilado = new RegExp(regexNIT);
What is the regex to check if input string is NOT lowercase only, it is NOT uppercase only and does NOT contain numbers.
Validation must fail
SIMO TEST
SIMO344
simo
simo3432
These are ok
SIMO test
Simo
Welcome to Stackoverflow
When posting a question, please make sure to include your attempts, so that we can help guide you to an answer. This website is not meant to give you the answer, but to help guide you to an answer, or to explain your error. It's more rewarding to help you if we are simply guiding you and not giving you the answer. You'll probably get more response too. Please remember that when posting next time.
I tried to explain regular expressions in JavaScript, and tried to guide you through the logic in my answer.
Your case
You can use the .test function of a RegExp to test if a string matches a regular expression. You can then invert that result to check if the string does not contain it. Each of the cases you mentioned is a separate expression, which can be joined by the | operator.
Testing if a string is lowercase only:
In a RegExp, a - can be used to indicate a range of characters. There are already specially assigned codes for commonly used ranges, such as \s for a white space. The + operator means one or more. The ^ means starts at the beginning of the line(string) and $ means starting the end.
^[a-z\s]+$
Testing if a string is uppercase only:
This is the exact same as the lowercase case, but the character range is for uppercase letters:
^[A-Z\s]+$
Testing for digits
The regex code \d is short for a range of digits (you can essentially think of it as [0-9], but it also accounts for unicode).
\d
Putting it all together
^[a-z\s]+$|^[A-Z\s]+$|\d
And in a condition, it would be:
if (!/^[a-z\s]+$|^[A-Z\s]+$|\d/.test(your_string_here)) {
// the string isn't uppercase only, lowercase only
// and doesn't contain a digit
}
Please see the below code snippet. Modify as per your requirement.
function validate(strInput) {
var re = /\d/;
if(re.exec(strInput)===null){
re = /^(?!.*[a-z\d]).+$/;
if(re.exec(strInput)===null){
re = /^[A-Z][a-z]*/;
if(re.exec(strInput)!==null)
return re.exec(strInput);
}
}
return false;
};
console.log(validate("SIMO TEST"));
console.log(validate("SIMO344"));
console.log(validate("Simo"));
console.log(validate("simo"));
console.log(validate("simo3432"));
console.log(validate("SIMO2 TEST"));
console.log(validate("Simo3"));
console.log(validate("SIMO test"));
function CheckPassword() {
var inputtxt = $('#text12').val();
console.log(inputtxt)
var passw = /(?=.*[a-z])(?=.*[A-Z]).{6,20}$/;
var passWN = /\d/;
if (inputtxt.match(passw)) {
if (!inputtxt.match(passWN)) {
alert('Correct, try another...')
return true;
} else {
alert('Wrong...!')
return false;
}
} else {
alert('Wrong...!')
return false;
}
}
I am trying to write some Javascript to hide some elements that contain only carriage returns. I appreciate that the correct way to solve this problem would be to stop these elements being created, but unfortunately that is not possible in this instance. I am trying to user a regular expression to search for the unwanted elements but am not having much luck. The function I have written is as follows:
function HideEmptyP()
{
var patt = (\\r)
for(var i = 0;i<desc[i].length;i++);
{
var desc[i] = document.getElementsByClassName('sitspagedesc');
var result[i] = patt.test(desc[i]);
if (result[i] == true)
{
desc[i].style.display='none';
}
else
{
alert("No Match!");
}
}
The error I'm getting in the Web Console is 'Syntax Error: Illegal Character'.
Grateful for any ideas on how to solve this.
Thanks in advance.
I am trying to write some Javascript to hide some elements that contain only carriage returns.
There's no need for a regular expression for that, just compare the element's innerHTML property to "\\r", e.g.:
if (demo[i].innerHTML === "\\r") {
// Remove it
}
But beware that some browsers may transform a single carriage return. You might want to check for "\\r", "\\n", and just a space. To do that, you might want to use a regular expression.
Your regular expression literal ((\\r)) is just completely invalid, it's worth reading up on them to learn the correct syntax. To write a regular expression literal in JavaScript, you use / as the delimiter. So: /\\r/. To test that a string contains only \r, \n, or space, you can use /^[\r\n ]+$/ (which requires there be at least one character that matches, and uses ^ to indicate start-of-string, and $ to indicate end-of-string):
if (demo[i].innerHTML.match(/^[\r\n ]+$/) {
// Remove it
}
The reason you are getting Syntax error is because the declaration
var patt = (\r)
is incorrect it should be somethign like var patt = '\r';
Also the whole for loop is wrong.
You should define demo before you start the for loop not inside it, and result need not be an array but just a normal variable
Your litteral seems odd.
Try var patt = /\r/;
var patt=/\n/gi
should work.
extra i flag to denote case insensitive.
g for global search.
Trying to check input against a regular expression.
The field should only allow alphanumeric characters, dashes and underscores and should NOT allow spaces.
However, the code below allows spaces.
What am I missing?
var regexp = /^[a-zA-Z0-9\-\_]$/;
var check = "checkme";
if (check.search(regexp) == -1)
{ alert('invalid'); }
else
{ alert('valid'); }
However, the code below allows spaces.
No, it doesn't. However, it will only match on input with a length of 1. For inputs with a length greater than or equal to 1, you need a + following the character class:
var regexp = /^[a-zA-Z0-9-_]+$/;
var check = "checkme";
if (check.search(regexp) === -1)
{ alert('invalid'); }
else
{ alert('valid'); }
Note that neither the - (in this instance) nor the _ need escaping.
This is the most concise syntax I could find for a regex expression to be used for this check:
const regex = /^[\w-]+$/;
You shouldn't use String.match but RegExp.prototype.test (i.e. /abc/.test("abcd")) instead of String.search() if you're only interested in a boolean value. You also need to repeat your character class as explained in the answer by Andy E:
var regexp = /^[a-zA-Z0-9-_]+$/;
Got stupid error. So post here, if anyone find it useful
[-\._] - means hyphen, dot and underscore
[\.-_] - means all signs in range from dot to underscore
Try this
"[A-Za-z0-9_-]+"
Should allow underscores and hyphens
try this one, it is working fine for me.
"^([a-zA-Z])[a-zA-Z0-9-_]*$"
Don't escape the underscore. Might be causing some whackness.