How can I determine if a string only contains spaces, using javascript? - javascript

How can I determine if an input string only contains spaces, using javascript?

Another good post for : Faster JavaScript Trim
You just need to apply trim function and check the length of the string. If the length after trimming is 0 - then the string contains only spaces.
var str = "data abc";
if((jQuery.trim( str )).length==0)
alert("only spaces");
else
alert("contains other characters");

if (!input.match(/^\s*$/)) {
//your turn...
}

Alternatively, you can do a test() which returns a boolean instead of an array
//assuming input is the string to test
if(/^\s*$/.test(input)){
//has spaces
}

if(!input.match(/^([\s\t\r\n]*)$/)) {
blah.blah();
}

The fastest solution is using the regex prototype function test() and looking for any character that is not a space or a line break \S :
if (/\S/.test(str))
{
// found something other than a space or a line break
}
In case that you have a super long string, it can make a significant difference.

Related

check whether csv form or not [duplicate]

What is the regular expression to validate a comma delimited list like this one:
12365, 45236, 458, 1, 99996332, ......
I suggest you to do in the following way:
(\d+)(,\s*\d+)*
which would work for a list containing 1 or more elements.
This regex extracts an element from a comma separated list, regardless of contents:
(.+?)(?:,|$)
If you just replace the comma with something else, it should work for any delimiter.
It depends a bit on your exact requirements. I'm assuming: all numbers, any length, numbers cannot have leading zeros nor contain commas or decimal points. individual numbers always separated by a comma then a space, and the last number does NOT have a comma and space after it. Any of these being wrong would simplify the solution.
([1-9][0-9]*,[ ])*[1-9][0-9]*
Here's how I built that mentally:
[0-9] any digit.
[1-9][0-9]* leading non-zero digit followed by any number of digits
[1-9][0-9]*, as above, followed by a comma
[1-9][0-9]*[ ] as above, followed by a space
([1-9][0-9]*[ ])* as above, repeated 0 or more times
([1-9][0-9]*[ ])*[1-9][0-9]* as above, with a final number that doesn't have a comma.
Match duplicate comma-delimited items:
(?<=,|^)([^,]*)(,\1)+(?=,|$)
Reference.
This regex can be used to split the values of a comma delimitted list. List elements may be quoted, unquoted or empty. Commas inside a pair of quotation marks are not matched.
,(?!(?<=(?:^|,)\s*"(?:[^"]|""|\\")*,)(?:[^"]|""|\\")*"\s*(?:,|$))
Reference.
/^\d+(?:, ?\d+)*$/
i used this for a list of items that had to be alphanumeric without underscores at the front of each item.
^(([0-9a-zA-Z][0-9a-zA-Z_]*)([,][0-9a-zA-Z][0-9a-zA-Z_]*)*)$
You might want to specify language just to be safe, but
(\d+, ?)+(\d+)?
ought to work
I had a slightly different requirement, to parse an encoded dictionary/hashtable with escaped commas, like this:
"1=This is something, 2=This is something,,with an escaped comma, 3=This is something else"
I think this is an elegant solution, with a trick that avoids a lot of regex complexity:
if (string.IsNullOrEmpty(encodedValues))
{
return null;
}
else
{
var retVal = new Dictionary<int, string>();
var reFields = new Regex(#"([0-9]+)\=(([A-Za-z0-9\s]|(,,))+),");
foreach (Match match in reFields.Matches(encodedValues + ","))
{
var id = match.Groups[1].Value;
var value = match.Groups[2].Value;
retVal[int.Parse(id)] = value.Replace(",,", ",");
}
return retVal;
}
I think it can be adapted to the original question with an expression like #"([0-9]+),\s?" and parse on Groups[0].
I hope it's helpful to somebody and thanks for the tips on getting it close to there, especially Asaph!
In JavaScript, use split to help out, and catch any negative digits as well:
'-1,2,-3'.match(/(-?\d+)(,\s*-?\d+)*/)[0].split(',');
// ["-1", "2", "-3"]
// may need trimming if digits are space-separated
The following will match any comma delimited word/digit/space combination
(((.)*,)*)(.)*
Why don't you work with groups:
^(\d+(, )?)+$
If you had a more complicated regex, i.e: for valid urls rather than just numbers. You could do the following where you loop through each element and test each of them individually against your regex:
const validRelativeUrlRegex = /^(^$|(?!.*(\W\W))\/[a-zA-Z0-9\/-]+[^\W_]$)/;
const relativeUrls = "/url1,/url-2,url3";
const startsWithComma = relativeUrls.startsWith(",");
const endsWithComma = relativeUrls.endsWith(",");
const areAllURLsValid = relativeUrls
.split(",")
.every(url => validRelativeUrlRegex.test(url));
const isValid = areAllURLsValid && !endsWithComma && !startsWithComma

How to remove comma from number which comes dynamically in .tpl file

i want to remove comma from a number (e.g change 1,125 to 1125 ) in a .tpl file.
The value comes dynamically like ${variableMap[key]}
var a='1,125';
a=a.replace(/\,/g,''); // 1125, but a string, so convert it to number
a=parseInt(a,10);
Hope it helps.
var a='1,125'
a=a.replace(/\,/g,'')
a=Number(a)
You can use the below function. This function can also handle larger numbers like 123,123,123.
function removeCommas(str) {
while (str.search(",") >= 0) {
str = (str + "").replace(',', '');
}
return str;
};
var s = '1,125';
s = s.split(',').join('');
Hope that helps.
✨ ES2021 ✨ added replaceAll, so no need for regular expression:
const str = '1,125,100.05';
const number = parseFloat(str.replaceAll(",", ""));
You can use Regular Expression to change as it is faster than split join
var s = '1,125';
s = s.replace(/,/g, '');
//output 1125
Incoming value may not always be a string. If the incoming value is a numeric the replace method won't be available and you'll get an error.
Suggest using isNaN to see if numeric, then assume string and do replacement otherwise.
if(isNaN(x)) {
x = parseInt(x.replace(/[,]/g,''));
}
(Not foolproof because 'not number' doesn't prove it is a string, but unless you're doing something very weird should be good enough).
You can also add other symbols to the character group to remove other stray chars (such as currency symbols).

Regular expression for allowing only a certain set of characters

I would like some help creating a regular expression for parsing a string on a textbox. I currently have these two javascript methods:
function removeIllegalCharacters(word) {
return word.replace(/[^a-zA-Z 0-9,.]/g, '');
}
$("#comment").keyup(function() {
this.value = removeIllegalCharacters(this.value);
});
I would like to replace my /[^a-zA-Z 0-9,.]/g regex for one that would accept only the following set of characters:
a-z
A-Z
0-9
áéíóúü
ÁÉÍÓÚÜ
ñÑ
;,.
()
- +
It's probably pretty simple, but I have close to none regex skills. Thanks in advance.
Just add those characters in.
function removeIllegalCharacters(word) {
return word.replace(/[^a-zA-Z 0-9,.áéíóúüÁÉÍÓÚÜñÑ();+-]/g, '');
}
return word.replace(/[^a-zA-Z0-9áéíóúüÁÉÍÓÚÜñÑ\(\);,\.]/g, '');
You may have to use the hex escape sequence (\x##) or unicode escape sequence (\u####) for some of the non standard letters, but that will give you a good start. Or, slightly simplified:
return word.replace(/[^\w\dáéíóúüÁÉÍÓÚÜñÑ\(\);,\.]/g, '');
If I've understood your requirements correctly, you want to allow only the listed char and you want to delete rest all char. If that is the case you can simply extend your char class as:
function removeIllegalCharacters(word) {
return word.replace(/[^a-zA-Z0-9áéíóúüÁÉÍÓÚÜñÑ;,.()]/g, '');
}
Did you try with: [^a-zA-Z 0-9;,.áéíóúüÁÉÍÓÚÜñÑ()]

How to use regEx to return false when data not in range?

Sample data: Hello I'm 301
I need a regex to allow A-Z a-z 0-9 and space(s) only.
All other characters are not allowed. If detected, return false to javascript.
Based on the sample data above, it should return false because got a character which is not accetable===> '
How to write this in js.
I suggest the regex:
/^[A-Z0-9 ]+$/i.test(someinput);
This ensures that the input ONLY consists of the characters mentioned in the regex, by "anchoring" the regex from start-of-the-string (indicated by "^") until the end of string ("$").
The trailing "/i" on the regex makes it a case-insensitive match, relieving specification of both cases of the letters.
Any string in Javascript has a match() function that accepts a regex and returns null if it doesn't match.
For instance, if you have:
var s = "Hello I'm 301";
you can test it with:
if (s.match(/^[a-z0-9\s]*$/i))
alert("string is ok!");
else
alert("string is bad!");
On to the regex: /^[a-z0-9\s]*$/i
The caret(^) at the beginning and the dollar ($) at the end are anchors. They mean "beginning of string" and "end of string".
They force the regex to cover the entire string, not just portions. The square brackets define a character range: letters and numbers, and also space.
Without the caret and the dollar (the anchors), your regex would have matched any valid character and would have returned true.
The final "i" is a regexp option, meaning "case insensitive".
Hope that helps!
Try this
function check(s){
return /^[A-Za-z0-9 ]+$/.test(s);
}
You'll probably want to use: /[A-Za-z0-9 ]*/.test(someInputString)
--edit: as noted in comments and other answers, the regex should be /^[A-Za-z0-9 ]*$/
You need to create the Javascript Regex object first.
var MyRegex = new RegExp(/^[a-zA-Z0-9\s]+$/)
or simply
var MyRegex = /^[a-zA-Z0-9\s]+$/
You can then use this to test, which will return a boolean
var MyString = "Hello I'm 301"
if (MyRegex.test (MyString))
{
// Would be true here
}
else
{
// Would be false here
// Would fall through to here due to '
}
I believe you can also do /^[a-zA-Z0-9\s]+$/.text(MyString)
Try this:
var x = 'Hello I\'m 301';
var z = x.match(/^[A-Za-z0-9\s]+$/g);
alert(z);
x = 'Hello Im 301';
var y = x.match(/^[A-Za-z0-9\s]+$/g);
alert(y);
Don't forget to escape the single quote in the test string :)
You can return true/false by checking for null after the regex match, if the sample string fails the match then the result is null.

Javascript regular expression match on string followed by number?

I have a string of the format: string:num where num is any number but string is a known string that I need to match on. I'd like to have this in an if statement as:
if( it matches 'string:' followed by a number) {
//do something
}
You want ...
if (stringYouHave.match(/^string:([0-9]+)$/)) {
// do something
}
This includes:
^ beginning of the string
string: the literal "string:" you mentioned
(.....) This subexpression, which you can refer to later if you need to know which number is in the string (though in this particular case, you could also just replace 'string:' with '')
[0-9] a character between 0 and 9 (i.e., a digit)
+ Must have at least one "of those" (i.e., digits mentioned above), but can have any number
$ end of the string
if( it.match(/^string:\d+$/) ( {
...
}
If you want only to check if the input string matches the pattern, you can use the RegExp.test function:
if (/^string:[0-9]+$/.test(input)){
//..
}
or with the String.search function:
if (input.search(/^string:[0-9]+$/) != -1){
//..
}
If you want to validate and get the number:
var match = input.match(/^string:([0-9]+)$/),
number;
if (match){
number = +match[1]; // unary plus to convert to number
// work with it
}
The above is good for integer numbers; if you want floating point numbers, or even scientific notation (as understood in C-like languages), you'll want something like this:
if (stringYouHave.match(/^string:[+-]?[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?$/))
{
// do something
}
You can remove the first [+-]? if you don't care about sign, the (.[0-9]+)? if you don't care about floating points, and the ([eE][+-]?[0-9]+)? if you don't care about scientific notation exponents. But if there's a chance you DO want to match those, you want to include them as optional in the regex.
if(teststring.match(new RegExp("^" + knownstring + ":\d+$"))) {
// some code
}
if(!!"string:5456".match(/^string:\d+$/)) { ... }
Number is a integer in the example above.

Categories

Resources