Check if string begins with something? [duplicate] - javascript

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.

Related

How to add variable inside a Character Class using javascript?

I need to add a variable inside a Character Class when using javascript regular expression. What I tried did not work. What the correct syntax for accomplishing this.
For example,
if(/[variable]/.test(Log))
{
}
You can use the following syntax
var re = new RegExp(variable);
and then use
re.test(Log)
Try this instead:
var regex = new RegExp(variable);
if(regex.test(Log)){
// your logic
}
Hope this will help !!
a='.*'
var patt=new RegExp(a);
patt.test('asdsd')
Actually,
if(/[variable]/.test(Log)) {
}
Is equivalent to:
if(new RegExp("["+variable+"]").test(Log)) {
}
Explanation:
Whenever you use a regex with the // notation, such as:
/[\d*]"+/
You can use the RegExp object and pass the regex as a escaped string. This way, the above regex is equivalent to:
new RegExp("[\\d*]\"+")
The modifiers can be passed as second argument. So that /anything/gm is the same as new RegExp("anything", "gm").

Get code of methods while iterating over object

I know in javascript I can iterate over an object to get all of it's properties. If one or more of the properties is a method, is it possible to see what code is in the method instead of just the method name? E.g.
var a = someobject;
for (property in a) {
console.log(property);
}
Is it possible to get method code in a way similar to this? Thank you in advance.
You need to use toString, per the standard. i.e:
//EX:
var a = {method:function(x) { return x; }};
//gets the properties
for (x in a) {
console.log(a[x].toString());
}
You can also use toSource but it is NOT part of the standard.
PS: attempting to reliably iterate through an object with a for : loop is nontrivial and dangerous (for..in only iterates over [[Enumerable]] properties, for one), try to avoid such constructs. I would ask why, exactly, are you doing this?
Yes. It actually works. Try:
var a = {};
a.id = 'aaa';
a.fun = function(){alert('aaa');}
for (x in a) {
var current = a[x].toString();
if(current.indexOf('function') == 0){
current = current.substring(current.indexOf('{')+ 1, current.lastIndexOf('}'));
}
console.log(current);
}
But it will not work for browser native code.
You can use the toString method on the function
i.e.
function hello() {
var hi = "hello world";
alert(hi);
}
alert(hello.toString());​
Update: The reason it wasn't working in JSFiddle was because I forgot to add the output inside of either console.log or alert - http://jsfiddle.net/pbojinov/mYqrY/
As long as a is an object, you should be able to use the square bracket notation and query a value from by argument with the same name as the objects property. For example:
a[ property ];
If you log typeof( property ), it will return "string" which is what we want.

How can I check if my string contains a period in JavaScript?

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!";}

Calling javascript function with an objectstring in dot notation

Suppose I have the string:
var string = "function";
With
window[string];
I can call a function with the name of "function".
But, when I have:
var string2 = "function.method.weHaveTogoDeeper";
it should call
window["function"]["method"]["weHaveTogoDeeper"]
I can't do:
window[string2]
in this case. I dont know the number of "." in the string, so I need some kind of routine.
you can split the string across . by using the String.split method:
var string2 = "function.method.weHaveTogoDeeper";
var methods = string2.split(".");
In this examples, methods will be the array ["function","method","weHaveTogoDeeper"]. You should now be able to do a simple iteration over this array, calling each function on the result of the previous one.
Edit
The iteration I had in mind was something like this:
var result = window;
for(var i in methods) {
result = result[methods[i]];
}
In your example, result should now hold the same output as
window["function"]["method"]["weHaveTogoDeeper"]
function index(x,i) {return x[i]}
string2.split('.').reduce(index, window);
edit: Of course if you are calling functions from strings of their names, you are likely doing something inelegant which would be frowned upon, especially in a collaborative coding settings. The only use case I can think of that is sane is writing a testing framework, though there are probably a few more cases. So please use caution when following this answer; one should instead use arrays, or ideally direct references.
I wrote one a while back:
function RecursiveMapper(handlerName, stack) {
// check if empty string
if(!handlerName || handlerName === '' || (handlerName.replace(/\s/g,'') === '')) return null;
var buf = handlerName.split('.');
stack = stack || window;
return (buf.length === 1) ? stack[buf[0]] : this.RecursiveMapper(buf.slice(1).join('.'), stack[buf[0]]);
}
Call it like this: RecursiveMapper(window[string2]);
This one also checks if the function is defined in window scope first and returns the global one fi found.

how to compare two elements in jquery [duplicate]

This question already has answers here:
How can I test if two jQuery wrapped DOM elements are the same? [duplicate]
(3 answers)
Closed 7 years ago.
var a=$('#start > div:last-child');
var b=$('#start > div.live')[0];
alert(a==b)
alert(a==$(b))
It's always false. How can you compare two elements in jQuery?
thanks
For the record, jQuery has an is() function for this:
a.is(b)
Note that a is already a jQuery instance.
You could compare DOM elements. Remember that jQuery selectors return arrays which will never be equal in the sense of reference equality.
Assuming:
<div id="a" class="a"></div>
this:
$('div.a')[0] == $('div#a')[0]
returns true.
Every time you call the jQuery() function, a new object is created and returned. So even equality checks on the same selectors will fail.
<div id="a">test</div>
$('#a') == $('#a') // false
The resulting jQuery object contains an array of matching elements, which are basically native DOM objects like HTMLDivElement that always refer to the same object, so you should check those for equality using the array index as Darin suggested.
$('#a')[0] == $('#a')[0] // true
a.is(b)
and to check if they are not equal use
!a.is(b)
as for
$b = $('#a')
....
$('#a')[0] == $b[0] // not always true
maybe class added to the element or removed from it after the first assignment
Random AirCoded example of testing "set equality" in jQuery:
$.fn.isEqual = function($otherSet) {
if (this === $otherSet) return true;
if (this.length != $otherSet.length) return false;
var ret = true;
this.each(function(idx) {
if (this !== $otherSet[idx]) {
ret = false; return false;
}
});
return ret;
};
var a=$('#start > div:last-child');
var b=$('#start > div.live')[0];
console.log($(b).isEqual(a));
The collection results you get back from a jQuery collection do not support set-based comparison. You can use compare the individual members one by one though, there are no utilities for this that I know of in jQuery.

Categories