I need to validate a string that it's an actual number.
let str = '\n2';
But Number(str) returns 2 instead of NaN.
How can I check if the given string contains any backslash?
\n inside a string literal is interpreted as a newline character, and newline characters, like all space characters, are just skipped over when you try to turn the string into a number:
// these are all whitespace characters
console.log(
Number(' 5'),
Number('\n5'),
Number('\t5'),
);
If you want to extract a number only if the string contains only number characters and nothing else, I'd match digits with a regular expression instead:
const extractNum = str => {
const match = str.match(/^\d+$/);
return match
? Number(match[0])
: NaN;
};
console.log(
extractNum('\n5'),
extractNum('5')
);
To permit decimals as well:
const extractNum = str => {
const match = str.match(/^\d*(?:\.\d+)?$/);
return match
? Number(match[0])
: NaN;
};
console.log(
extractNum('\n5'),
extractNum('5'),
extractNum('0.123'),
extractNum('.55')
);
Related
I want to find a string in style of '/89/'
Let's say I have this string: '78/12/98 something else' and want to transform it into 'something else'.
And let's assume that not every string has to contain this type of expression(if the search function returns -1 we do nothing).
How to do this?
let string = '78/12/98 something else';
let index = string.search(look for description);
if(index!=-1){
string = string.substring(index+5);
}
console.log(string);
// OUTPUT: 'something else'
let string2 ='no double backslashes with digits between them';
index = string.search(look for description);
if(index!=-1){
string = string.substring(index+5);
}
console.log(string2);
// OUTPUT: 'no double backslashes with digits between them';
The pattern you are looking for is
Two digits / Two digits / Two digits space anything endline
\d\d/\d\d/\d\d\s(.*$)
or maybe
Zero or Two digits / Zero or Two digits / Zero or Two digits space anything endline
\d{0,2}/\d{0,2}/\d{0,2}\s(.*$)
replace with
\1 It will replace with anything it matched inside ().
For JS you can do as follow
let string = '78/12/98 something else';
let patt = /\d{0,2}\/\d{0,2}\/\d{0,2}\s/; // Creates a regex patern
string = string.replace(patt, ''); // replace finds with ''
enter image description here
I have a text string that can be as follows let str = '10x2.34' from which I would like to get only the numbers so try the following:
str.match(/\d+/g)
This ignores the characters and returns the numbers to me, but it only works for whole numbers, so how could I get the whole numbers and decimals, which can come in the following ways: let str = '10x2.34' or let str = '10x2,34'
Match digits with \d and punctuation with \. or , :
str.match(/[\d\.,]+/g)
const regex = /[\d\.,]+/g
console.log( "10x2.34".match(regex) ) // ["10","2.34"]
console.log( "10x2,34".match(regex) ) // ["10","2,34"]
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
I try to transform string using String replace method and regular expression. How can I remove underscores in a given string?
let string = 'court_order_state'
string = string.replace(/_([a-z])/g, (_, match) => match.toUpperCase())
console.log(string)
Expected result:
COURT ORDER STATE
You could use JavaScript replace function, passing as input:
/_/g as searchvalue parameter (the g modifier is used to perform a global match, i.e. find all matches rather than stopping after the first one);
(blank space) as newvalue parameter.
let string = 'court_order_state'
string = string.replace(/_/g, ' ').toUpperCase();
console.log(string);
In your code you could match either and underscore or the start of the string (?:_|^) to also match the first word and match 1+ times a-z using a quantifier [a-z]+
Then append a space after each call toUpperCase.
let string = 'court_order_state';
string = string.replace(/(?:_|^)([a-z]+)/g, (m, g1) => g1.toUpperCase() + " ");
console.log(string)
let string = 'court_order_____state'
string = string.replace(/_+/g, ' ').toUpperCase()
console.log(string)
It can be as simple as the below:
let string = 'court_order_state'
string = string.replace(/_/g, ' ').toUpperCase();
console.log(string);
Here the 'g' represents global, whereas the '/' is surrounded by what we're looking for.
Instead of matching the first character just after every _ and making them uppercase (from the regex that you have used), you can simply convert the entire string to uppercase, and replace the _ with space by the following:
let string = 'court_order_state';
string = string.toUpperCase().replace(/_+/g, " ");
console.log(string);
Sorry if the wording is bad. So I'm trying to find out how to pass in a string match of multiple characters long into my dynamic regex expression.
The regex in my else statement works with 1 character being passed in so I'm trying to do the same thing except with multiple characters being passed in the first if statement.
const delimiter = str.slice(0, str.indexOf('\n'));
const strLength = delimiter.length;
if (delimiter[0] === '[' && delimiter.charAt(strLength - 1) === ']') {
const customDelimiter = delimiter.slice(delimiter.indexOf(delimiter[1]), delimiter.indexOf(delimiter.charAt(strLength - 1)));
console.log(customDelimiter) // => '***'
const regex = new RegExp(`,|\\n|\\${customDelimiter}`,'g');
return strArr = str.split(regex).filter(Boolean);
} else {
const firstChar = str.slice(0, 1); // => '*'
const regex = new RegExp(`,|\\n|\\${firstChar}`,'g');
return strArr = str.split(regex).filter(Boolean);
}
So for example I want this string:
'[*]\n11***22***33' to equal 66 b/c it should split it into an array of [11, 22, 33] using the '*' delimiter. I get an error message saying: "SyntaxError: Invalid regular expression: /,|\n|***/: Nothing to repeat".
When you use * as delimeter in your regex, it becomes ,|\\n|\\|\*, which is the correct regex.
It matches ',' or '\n' or a '*' character.
For your string, it matches [***]\n11***22***33.
But when you use *** as a delimiter in your regex, it becomes ,|\\n|\\|\***, which is incorrect. Here it gets two unescaped * at the end. * in regex means 0 or more of the preceding pattern. You cannot have two of them together.
This is a special case because * has a special meaning in regex.
If you would have used any non-regex character, it would work.
A simpler solution would be to use javascript split function to easily get the desired result.
You could first split the string using \n.
let splitStr = str.split('\n');
// This would return ["[***]", "11***22***33"]
and then split the 1st index of the splitStr using the delimeter.
splitStr[1].split('***');
// splitStr[1].split(customDelimiter)
// This would return ["11", "22", "33"]
Using this you wouldn't need to use if or else statement to separate out single character delimiter and multiple character delimiter.