How to check pipeline and comma (|,) in a string using Regex [duplicate] - javascript

This question already has an answer here:
All characters in a string must match regex
(1 answer)
Closed 3 years ago.
I have to check whether a given string contains pipeline and comma (|,) in a string and throw error if it contain the same.throwing error part i can handle but facing issue while creating regex for this.
i have used this regex to validate it [^|,] but its not working.
String is "Equinix | Megaport" but my vregex is not throwing error as it contains | in it

In JavaScript, try:
var subject = "Equinix | Megaport";
if (/^[^|,]+$/.test(subject)) {
document.write('No bad character(s)');
} else {
document.write('Contains bad character(s)');
};
Also note that I slightly changed your pattern to include the + operator after your negated character class, which means match the character class between one and unlimited times.

Related

Regex pattern for //;\n2;3;4 [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 1 year ago.
I am trying to find a regex which supports a pattern like below:
String starts with //
String has a delimiter after //; (suppose ; is the delimiter)
String has \n after demiliter (//;\n)
Finally String contains any number of digits with that delimiter (//;\n2;3;4;5)
Could you help?
I tried ^//\\D+\\n.*$ but it doesn't work.
Thanks in advance!
Sample: //;\n2;3;4;5
Answer: [/]{2}[;]\\[n](\d[;]){1,999}\d
This will allow further combinations of a decimal followed by ;
\d is added at the end in the case a semicolon is not added judging by your sample
Okay based on your additional comment this could work. It's very messy but it may just get the job done.
var string = "//;\n2;3;4;5";
console.log(
string.replace(/[^0-9,.]+/g," ").trim().split(" ").map(function(x){return parseInt(x, 10);}).reduce(function(a, b){return a + b;}, 0)
);
Console log results in 14

Regex Expression for Firebase Cloud Messaging [duplicate]

This question already has answers here:
Match exact string
(3 answers)
Closed 2 years ago.
I'm trying to check the string entered by users to be used as a topic name for sending notifications with Firebase Cloud Messaging.
As I understand it, the only characters allowed in topic names are:
lowercase letters a to z
uppercase letters A to Z
digits 0 to 9
characters - _ . ~ %
The error message from Cloud Messaging when the topic name contains illegal characters is
Notification sent failed: { Error: Topic provided to sendToTopic() must be a string which matches the format "/topics/[a-zA-Z0-9-_.~%]+".
So I try to check for this in my JavaScript code to prevent users from entering the illegal characters. My understanding of checking the regex I obviously wrong though, as the test keeps validating invalid characters as being valid.
The code I'm using is as follows:
let sample = "Test Topic Name 20/20"
let trimmedSample = sample.split(' ').join('');
console.log("trimmedSample = " + trimmedSample);
validateString(trimmedSample);
function validateString(inputtxt) {
var letters = /[0-9a-zA-Z]+/;
if (letters.test(inputtxt)) {
console.log("name is Valid");
} else {
console.log("name is Invalid");
}
}
Even though the topic name includes the invalid '/' character, the check validates it as valid. In fact I'm struggling to find a character it says is invalid.
I'd be grateful to anyone who could point out what I'm going wrong?
Thanks
Your current regular expression checks of the string contains the sample. What you want to do is ensure that it complete matches it with:
var letters = /^[0-9a-zA-Z]+$/;
By using the ^ and $ you ensure that the regular expression must match the entire string for it to succeed, instead of also succeeding on a substring.

Remove empty characters, blank characters, invisible characters in jQuery [duplicate]

This question already has answers here:
Remove not alphanumeric characters from string
(10 answers)
Regular expression to remove anything but alphabets and '[single quote]
(1 answer)
javascript regex to return letters only
(6 answers)
Ignoring invisible characters in RegEx
(2 answers)
Closed 2 years ago.
I am performing a validation in html text box which should pass only alphabets(a-z/A-Z) and few special characters like (*,& etc..). Otherwise it should show error some error.
I had written a JavaScript function which does the same.
function removeInvalidCharacters(selectedElement) {
if (selectedElement && typeof selectedElement.val() !== typeof undefined && selectedElement.val() != "") {
selectedElement.val(selectedElement.val().replace(/[\u0000-\u001F]|[\u007F-\u00A0]/g, "").replace(/\\f/g, "").replace(/%/g,""));
}
}
I am filtering selectedElement before passing to the function removeInvalidCharacters.
$("#name").val(toASCII($("#name").val()));
var selectedElement = $("#name").val();
But now I am facing a scenario in which empty characters, blank characters, invisible characters and whitespace characters are bypassing my regex. I could see some invisible characters are present in my name field. I want to replace these characters.
In further investigation I could found that Invisible characters - ASCII
characters mentioned in this link are the culprits. I need to have a regex to catch them and replace them.
Eg: AAAAAAAAAAAA‎AAAAAAAAAAA is the value in text field. Now if we check $("#name").val().length, it gives 24 ,even though we could see only 23 characters. I need to remove that hidden character.
Please help me with this scenario. Hope my query is clear
UPDATE:
var result = selectedElement.replace(/[\u200B-\u200D\uFEFF]/g, ''); fixed my problem.
Thank you all for the support.
If you want to allow only (a-z/A-Z) like you mention, try this:
str = str.replace(/[^a-zA-Z]/g, '');
Include the chars you want to keep instead of the ones you do not want, since that list may be incomplete
Otherwise look here: Remove zero-width space characters from a JavaScript string
const val = `AAAAAAAAAAAA‎AAAA**AAAAAAA`;
const cleaned = val.replace(/[^A-Za-z*]/g,"");
console.log(val.length,cleaned.length);

RegExp vs /.../ [duplicate]

This question already has answers here:
JavaScript: RegExp constructor vs RegEx literal
(4 answers)
Closed 4 years ago.
I am trying to learn regular expressions in Javascript through this brilliant book "Eloquent Javascript" by Marijn Haverbeke. I am unable to figure out why some of these match and why some don't even though they seem fine. I don't know if I have misunderstood something or understood something partially. For example -
console.log(/'\d+'/.test("123"));
// This doesn't match
console.log(/'\d+'/.test("'123'"));
// This matches
let myRegEx = new RegExp("\d+");
console.log(myRegEx.test("123"));
//Doesn't match
console.log(myRegEx.test("'123'"));
//Doesn't match either
Also, why are '' required inside "" for the string to be matched?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
The correct code:
console.log(/\d+/.test("123"));
or
let myRegEx = new RegExp("\\d+");
console.log(myRegEx.test("123"));
You have to add \ for the new RegExpr because "\\d+" is a string interpreted as "\d+"
Also, why are '' required inside "" for the string to be matched?
They are not:
/\d+/ matches "A number, one or more that one time"
/'\d+'/ matches "A quote, then A number, one or more that one time, then a quote"
So:
/\d+/.test("123") === true
/'\d+'/.test("123") === false (because ' are not found)
/\d+/.test("'123'") === true (because numbers are found)
/'\d+'/.test("'123'") === true
\ is an escape character in string literals as well as regular expressions.
"\d+" is the same as "d+" so you are testing for 1 or more instances of the character d.

How do I properly use RegExp in JavaScript and PHP? [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 6 years ago.
How do I properly use RegExp?
var text = "here come dat boi o shit waddup";
var exmaple = /[a-zA-Z0-9 ]/; // allowes a-zA-Z0-9 and whitespaces but nothing else right?
example.test(test); // would return true right?
text = "%coconut$§=";
example.test(text); // would return false right?
//I know this is very basic - I started learnig all this about week ago
Are JS RegExp's the same as PHP RegExp's?
How do I define banned characters instead of defining allowed characters?
How do I make it so that the var text has to contain 3 (or more) numbers/letters?
How do I include / or ",'$ etc. in my pattern?
No.
Use ^ character (i.e. [^abc] will exclude a, b and c)
Use [A-Za-z]{3} for letters and \d{3} for digits. If you want 3 or more, use \d{3,}
Use escape character (\/, \', \", '\$')

Categories

Resources