I want to be able to detect if a string has a . in it and return true/false based on that.
For example:
"myfile.doc" = TRUE
vs.
"mydirectory" = FALSE;
Use indexOf()
var str="myfile.doc";
var str2="mydirectory";
if(str.indexOf('.') !== -1)
{
// would be true. Period found in file name
console.log("Found . in str")
}
if(str2.indexOf('.') !== -1)
{
// would be false. No period found in directory name. This won't run.
console.log("Found . in str2")
}
Just test the return value of the indexOf method: someString.indexOf('.') != -1. No need for a regex.
I know this is an old question, but here is a new way to do it (not supported in older browsers -> can I use):
str.includes('.'); //returns true or false
docs
Some simple regex will do.
if (myString.match(\.)) {
doSomething();
}
Just to add to what's already been said:
There are differing opinions on whether or not this is a good idea, but you can extend all String instances with a contains method if you like:
String.prototype.contains = function(char) {
return this.indexOf(char) !== -1;
};
I tend to like this sort of thing, when it's (relatively) unambiguous what a method will do.
Use indexOf. It returns an integer showing the position of a substring, or -1 if it isn't found.
For example:
var test="myfile.doc"
if (test.indexOf('.')) {alert("Period found!";}
else {alert("Period not found. Sorry!";}
Related
I'm not asking for substr, indexOf, includes, substring functions; it's the opposite of that like "apple".isIncludedIn("apple tree")
Is there a function that checks the other way around the usual way of checking? If a substring is contained in a string in javascript where the substring is the object of action.
Because I want to be able to safely check without the null exception issue for the case that I know the substring but the string to check on is a variable, e.g.
let arr = [null, "apple tree"]
let str = arr[Math.floor(Math.random() * arr.length)];
if ("apple".isIncludedIn(str)) {
console.log("It is!");
}
Because str.includes("apple") can result to Cannot read property 'includes' of null
[Additional Note]
I'm aware that I can do (str && str.includes()) or ((str || '').includes()) but these seem "hacky" to me (personal opinion).
Just reverse the argument and the string being called on. To achieve
"apple".isIncludedIn("apple tree")
do
"apple tree".includes("apple")
To also permit nulls without throwing, use optional chaining if you want to be concise.
let arr = [null, "apple tree"]
let str = arr[Math.floor(Math.random() * arr.length)];
if (str?.includes("apple")) {
console.log("It is!");
} else {
console.log("It's not");
}
For obsolete browsers that don't understand optional chaining, just like all uses of modern syntax, use Babel to transpile your code down to ES6 or ES5 for production automatically.
Using || operator will solve your issue.
(str || '').includes("apple")
If str is null, it checks with '' so returns false
If str is present, it returns if string contains substring
I'm looking for a way to do the following:
$("#a" || "#b").val() === ""
as opposed to:
$("#a").val() === "" || $("#b").val() === ""
Any ideas?
Thanks in advance!
For two elements, I believe your example is about as short as you can make it and its meaning is clear. However, if you wish to repeat such logic or evaluate more elements, you might be able to improve upon it by creating a simple function to evaluate if any items in a set match a condition.
Extending jQuery
$.fn.any = function (evaluator) {
var items = $(this);
for (var i = 0; i < items.length; i++) {
if (evaluator(items[i]) === true) {
return true;
}
}
return false;
};
Demo: http://jsfiddle.net/xE76y/1/
This is similar to the Any() method implemented in the .Net LINQ library* (and I'm sure is implemented in other libraries, especially those geared towards functional programming). In c#, you would call such a method:
enumerable.Any( o => o.Value == "" );
JavaScript's syntax (sadly) isn't as concise; you end up with something like:
array.any( function(o){ return o.value === ""; } );
So far, this hasn't saved you anything. However, if you want to iterate over a large number of elements, it becomes much more elegant.
// there could be zero inputs or 100 inputs; it doesn't matter
var result = $("input").any(function (o) {
return o.value === "";
});
Native Solution
Note that we aren't relying on jQuery in our any() method. You could also consider a native JavaScript solution such as the Array.some() method.
some() executes the callback function once for each element present in
the array until it finds one where callback returns a true value. If
such an element is found, some immediately returns true.
Demo: http://jsfiddle.net/xE76y/2/
var result = jQuery.makeArray($("input")).some(function (o) {
return o.value === "";
});
Since this is an array method, it only works on an array. This unfortunately means that document.getElementsByTagName("input").some(...) will not work since getElementsByTagName() returns a NodeList.
Of course, you could push whatever you wanted into an array and call some() on that array. The call to jQuery.makeArray() in the example is just for convenience.
Abstracting the Evaluation Functions
Demo: http://jsfiddle.net/xE76y/3/
Perhaps the evaluation functions (such as testing for an empty string) will be reused. These can be abstracted further.
// ideally, this should NOT be left in global scope
function isEmpty(input) {
return input.value === "";
}
// the check now fits nicely in one line.
if ($("input").any(isEmpty)) {
alert("At least one input is empty.");
}
The resulting method calls are quite clean: $("#a, #b").any(isEmpty) and $("input").any(isEmpty)
* Also worth noting that LINQ has been recreated for JavaScript.
Try like this instead:
if ($('#a,#b').is(':empty'))
{
alert("Either a or b is Empty!");
}
Try my demo
Edit:
If it is an input type like a textbox then it would be a little bit bulky but will achieve the same effect:
if ($.inArray("",[ $("#a").val(), $("#b").val() ])>=0)
{
alert("Either a or b is Empty!");
}
See another Demo
If you want to avoid duplication of the empty string "", you could do this:
if ($.inArray([ $("#a").val(), $("#b").val() ], ""))
Or if you only want to select once with jQuery:
if ($.inArray($("#a, #b").map(function() { return this.value; }), ""))
But I wouldn't use either of these myself. They are arguably both less efficient, more contrived, and certainly less readable than the "easy" way!
I'm not an expert in javaScript, but have you cross checked with :
http://api.jquery.com/multiple-selector/
jQuery selector regular expressions
Also, one way would be using the .each function as in
jQuery Multiple ID selectors
How can I with jquery check to see if a key/value exist in the resulting json after a getJSON?
function myPush(){
$.getJSON("client.php?action=listen",function(d){
d.chat_msg = d.chat_msg.replace(/\\\"/g, "\"");
$('#display').prepend(d.chat_msg+'<br />');
if(d.failed != 'true'){ myPush(); }
});
}
Basically I need a way to see if d.failed exist and if it = 'true' then do not continue looping pushes.
You don't need jQuery for this, just JavaScript. You can do it a few ways:
typeof d.failed- returns the type ('undefined', 'Number', etc)
d.hasOwnProperty('failed')- just in case it's inherited
'failed' in d- check if it was ever set (even to undefined)
You can also do a check on d.failed: if (d.failed), but this will return false if d.failed is undefined, null, false, or zero. To keep it simple, why not do if (d.failed === 'true')? Why check if it exists? If it's true, just return or set some kind of boolean.
Reference:
http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/
Found this yesterday. CSS like selectors for JSON
http://jsonselect.org/
You can use a javascript idiom for if-statements like this:
if (d.failed) {
// code in here will execute if not undefined or null
}
Simple as that. In your case it should be:
if (d.failed && d.failed != 'true') {
myPush();
}
Ironically this reads out as "if d.failed exists and is set to 'true'" as the OP wrote in the question.
I have a JavaScript function that uses document.getElementById(). I want to upgrade it to be able to use jQuery selectors ($(this).parent().find("blah")), however it needs to be able to use the original method for backwards compatibility. Is there a way I can test if the argument passed to the function is a string (so I can use getElementById) or a jQuery object (not a string).
I could use .length, but is this a failsafe method of determining whether the argument is a string?
As long as I can test for strings, the jQuery branch can just go in an else - I don't need to make absolutely sure it's not a string, although it would be nice to test if it's jQuery too.
Thanks,
James
following code returns true:
"somestring".constructor == String
Object.prototype.toString.call(your_argument) == "[object String]"
Is this what you're after?
var str = "blah";
if (typeof str == "string") {
} else {
}
And length is definitely not the way to go. Arrays will also have a length property, not to mention any custom object could as well.
I think instanceOf is what you are looking for. See this post: What is the instanceof operator in JavaScript?
JavaScript has two kinds of strings. This checks for both kinds.
function isString (str)
{
return str instanceof String || typeof str === 'string';
}
This will throw always a ReferenceError, if the argument is undeclared although typeof would not throw an error, because JavaScript evaluates from left to right (see Short-circuit evaluation).
This question already has answers here:
How to check if a string "StartsWith" another string?
(18 answers)
Closed 3 years ago.
I know that I can do like ^= to see if an id starts with something, and I tried using that for this, but it didn't work. Basically, I'm retrieving a URL and I want to set a class for an element for path names that start in a certain way.
Example:
var pathname = window.location.pathname; //gives me /sub/1/train/yonks/459087
I want to make sure that for every path that starts with /sub/1, I can set a class for an element:
if (pathname ^= '/sub/1') { //this didn't work...
...
Use stringObject.substring
if (pathname.substring(0, 6) == "/sub/1") {
// ...
}
String.prototype.startsWith = function(needle)
{
return this.indexOf(needle) === 0;
};
You can use string.match() and a regular expression for this too:
if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes
string.match() will return an array of matching substrings if found, otherwise null.
A little more reusable function:
beginsWith = function(needle, haystack){
return (haystack.substr(0, needle.length) == needle);
}
First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.
String.prototype.beginsWith = function (string) {
return(this.indexOf(string) === 0);
};
Then you use it like this. Caution! Makes the code extremely readable.
var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
// Do stuff here
}
Have a look at JavaScript substring() method.