How do I write a regular expression for use in JavaScript that'll ensure the first and last characters of a string are always digits?
r = /\D+/g;
var s = "l10ddd31ddd5705ddd";
var o = r.test(s);
console.log(o);
So, 1KJ25LP3665 would return true, while K12M25XC5750 would return false.
You can have a regex like below:
/^\d(.*\d)?$/
The ^ to begin match from start of the string and $ to continue match till end of the string.
\d to match a digit at the beginning and the end.
.* to match zero or more characters in between.
We make the group 1 => (.*\d) optional with the ? metacharacter to optionally match zero or more characters ending with the digit till the end of the string. This would help if the string has only a single digit.
if(s.matches("\\d.*\\d"))
{
// Do what you want once both start and ending characters are digits
}
This solution achieves the same result without a Regex. It also takes care of empty strings or strings with only one character.
function startsAndEndsWithDigits(string)
{
if(string.length>0)//if string is not empty
{
var firstChar = string.split('')[0];//get the first charcter of the string
var lastChar = string.split('')[string.length -1];//get the last charcter of the string
if(firstChar.length>0 && lastChar.length>0)
{ //if first and last charcters are numbers, return true. Otherwise return false.
return !isNaN(firstChar) && !isNaN(lastChar);
}
}
return false;
}
Usage example:
startsAndEndsWithDigits('1KJ25LP3665'); //returns true
startsAndEndsWithDigits('K12M25XC5750');//returns false
startsAndEndsWithDigits(''); //returns false
startsAndEndsWithDigits('a'); //returns false
startsAndEndsWithDigits('7'); //returns true
Related
string = '1,23'
When a comma is present in the string, I want the regex to match the first digit (\n) after the comma e.g.2.
Sometimes the comma will not be there. When it's not present, I want the regex to match the first digit of the string e.g. 1.
Also, we can't reverse the order of the string to solve this task.
I am genuinely stuck. The only idea I had was prepending this: [,|nothing]. I tried '' to mean nothing but that didn't work.
You can match an optional sequence of chars other than a comma and then a comma at the start of a string, and then match and capture the digit with
/^(?:[^,]*,)?(\d)/
See the regex demo.
Details
^ - start of string
(?:[^,]*,)? - an optional sequence of
[^,]* - 0 any chars other than a comma
, - a comma
(\d) - Capturing group 1: any digit
See the JavaScript demo:
const strs = ['123', '1,23'];
const rx = /^(?:[^,]*,)?(\d)/;
for (const s of strs) {
const result = (s.match(rx) || ['',''])[1];
// Or, const result = s.match(rx)?.[1] || "";
console.log(s, '=>', result);
}
I have an input field to which I have tied a formatting function that is triggered whenever the field loses focus.
What I aim to achieve is that I remove all the leading zeros from an input and I did achieve that with the below line. However, when the user wants to enter a single 0 or something like 0000 I still want that field to end with the value 0 (single). With .replace(/^0+/, '') it would remove every zero and return just an empty string. Someone knows what regex could handle this?
const formatNumber = ($field) => {
var number = $field.val().replace(/\./g, '').replace(/\s/g, '').replace(/^0+/, '');
return number;
};
note: if(number === "") number = "0" is not an option.
edit1:: I noticed there seems to be a bit of confusion. e.g "0009825" need to become 9825 and not 09825. the only instance where i want a 0 up front is when the value is simply zero.
You ay use this regex replacement:
.replace(/^(?:0+(?=[1-9])|0+(?=0$))/mg, '')
RegEx Demo
RegEx Details:
^: Start
(?:: Start capture group
0+(?=[1-9]): Match 1 or more zeroes that must be followed by 1-9
|: OR
0+(?=0$): Match 1 or more zeroes that must be followed by one 0 and end
): End capture group
Replacement is empty string which will leave a single 0 if there are only zeroes in string otherwise will remove leading zeroes.
Alternative solution using a capture group:
str = str.replace(/^0+(0$|[1-9])/mg, '$1');
A simple reg exp with leading zeros and match one digit in a capture group
const cleanZeros = str => str.replace(/^0+(\d)/, '$1')
var tests = ["0009876","0", "0000", "9999", "0090000"]
tests.forEach( s => console.log(s, cleanZeros(s)))
I am trying to make ifcondition for a large number of chars.
I can use
if (str==!||str==#||str==#||str==$||str==^||str==&)
And so on, but this seems very inefficient. I would like to get the condition to work if the char is on of those:
!##%$^&()_-+=\?/.,'][{}<>`~
Is there is any shorter and more efficient way of doing it?
for (var c0 = 1; c0 > fn.length++; c0++) {
var str = fn.charAt(c0--);
if (str ==-"!##%$^&()_-+=\?/.,'][{}<>`~") {
}
}
I want the check to accrue on every single char from the string above.
You can use a regular expression character class to check if your character matches a particular character:
/^[\!##%$\^&\(\)_\-\+=\?\/\.,'\]\[\{\}\<\>`~]$/
Here I have escape special characters so that they get treated like regular characters.
See working example below:
const regex = /^[\!##%$\^&\(\)_\-\+=\?\/\.,'\]\[\{\}\<\>`~]$/,
charA = '#', // appears in char set
charB = 'A'; // doesn't appear in char set
console.log(regex.test(charA)); // true
console.log(regex.test(charB)); // false
Alternatively, if you don't want to use regular expressions you can instead put all your characters into an array and use .includes to check if your character is in your array.
const chars = "!##%$^&()_-+=\?/.,'][{}<>`~",
charArr = [...chars],
charA = '#', // is in char set
charB = 'A'; // isn't in char set
console.log(charArr.includes(charA)); // true
console.log(charArr.includes(charB)); // false
Just use regular expressions rather than manual single character checking.
const pattern = new RegExp("!##%$^&()_-+=\?\/.,'][{}<>`~");
const exists = pattern.test(str);
if (exists) {
// code logic for special character exists in string
}
First you can use split('') to split a string into an array of characters. Next you can use .some to check if a condition is true for at least one element in the array:
"!##%$^&()_-+=\?/.,'][{}<>`~".split('').some(x => x === str)
I have a string aa,bb\\,cc,dd. I need to split it by comma but only when the previous character is not backslash. So what I want is:
aa
bb\\,cc
dd
Since JavaScript regular expression doesn't support negative look back, I want to know how to solve it in this case. Thank you.
You may use this regex for match:
/(?=.)([^,\\]*(?:\\.[^,\\]*)*)(?:,|$)/gm
This regex ignores all escaped characters while matching substrings that have a comma or end of line at next positions.
RegEx Demo
RegEx Details:
(?=.): Make sure we don't match empty strings
([^,\\]*: Match 0 or more of any chars that are not , and \
(?:\\.[^,\\]*)*): Match \ followed by escaped character and then 0 or more of any chars that are not , and \.
(?:,|$): Match comma or end of line
const regex = /(?=.)([^,\\]*(?:\\.[^,\\]*)*)(?:,|$)/gm;
const str = `aa,bb\\,cc,dd`;
let m;
while ((m = regex.exec(str)) !== null) {
console.log(m[1]);
}
//=> [aa, bb\,cc, dd]
If you want to split by comma with a lookbehind assertion, you can split by all commas and then enforce the lookbehind assertion in a .reduce() while accumulating the array.
const str = 'aa,bb\\,cc,dd'
const values = str.split(/,/g).reduce((acc, str) => {
const lastIndex = acc.length - 1
if (lastIndex >= 0 && acc[lastIndex].endsWith('\\')) {
acc[lastIndex] += str
} else {
acc.push(str)
}
return acc
}, [])
console.log(values)
this program is supposed to test str, and if every letter in str has a '+' sign on both sides of it then the function should return true. Otherwise, it should return false. I keep getting the error "SyntaxError: invalid quantifier".
function SimpleSymbols(str) {
var boolean = false;
for(var i=1;i<(str.length-1);i++){
if(/\w/.test(str.charAt(i))){
if(str.charAt(i-1).match('+') && str.charAt(i+1).match('+')){
boolean = true;
}else{
boolean = false;
}
}
}
str = boolean;
return str;
}
match is used for regular expressions, so it's trying to convert '+' to a regular expression, but it's failing because /+/ isn't a valid regular expression (it should be '\\+' or /\+/). But it's easier to just directly test each character, like this:
if(str.charAt(i-1) == '+' && str.charAt(i+1) == '+'){
Also note that /\w/ matches any 'word' character, which includes letters, numbers, and underscores. To mach just letter characters use should use /[a-z]/i (the i at the end makes it case-insensitive, so it will also match upper-case letters).
But it seems a lot simpler to invert the condition. Just test to see if the string contains any letter not surrounded by + signs or a letter at the beginning or end of the string, and return false if it does, like this:
function SimpleSymbols(str) {
return ! /(^|[^+])[a-z]|[a-z]([^+]|$)/i.test(str);
}
Much easier:
function SimpleSymbols(str) {
return !str.match(/[^+]\w/) && !str.match(/\w[^+]/);
}
The main problems with your function are:
You don't test if the first and last characters are letters. It should be safe to run your for loop from index 0 to < str.length because even though this will result in a str.charAt(-1) and str.charAt(str.length) when testing for '+' these just return "" rather than an error. Or of course you could continue with testing from the second character through to the second last in the loop and add an additional test for the first and last characters.
The .match() method does a regex match, so it tries to convert '+' to a regex and of course + has special meaning within a regex and doesn't match the literal. I'd suggest just using === '+' instead, though you could use .match(/\+/).
You are returning whatever value the boolean variable ends up with, which means your function is ignoring the tests on all but the second-last character in the string. You should return false immediately if you find a letter that doesn't have '+' around it.
Your question asked about "letters", but /\w/ doesn't test for a letter, it tests for letters or digits or underscores. If you actually want just letters use /[a-z]/i.
(Also there's no point assigning str = boolean, because JS function parameters are passed by value so this assignment won't affect anything outside the function.)
So:
function SimpleSymbols(str) {
for(var i=0;i<str.length;i++){
if(/[a-z]/i.test(str.charAt(i))){
if(str.charAt(i-1)!='+' || str.charAt(i+1) != '+'){
return false;
}
}
}
return true;
}