简体   繁体   中英

How to invoke a function on a String in javascript?

Maybe this is weird, but I have one more question for the same GA API helper function. I need strings which will specify filter conditions, but I don't know how to use it properly. Basically I want to generate and return a string such as "ga:medium==organic" from this function call medium.equals(organic) where var organic = "organic" and var medium = "ga:medium" . I know how to work with the two strings to produce the output, and there are a lot more conditions to code for, but I just need to know how to invoke the function on the string medium and then how to use both the invoking object (string) and the arguments to return an output. Is what I'm asking possible?

You can add methods to the string object and then refer to this to access the string you're operating on.

String.prototype.equals = function(arg) {
    return this + "==" + arg;
}

var medium = "ga:medium";
var organic = "organic";
var output = medium.equals(organic);   // "ga:medium==organic"

Working demo: http://jsfiddle.net/jfriend00/hNLy6/

If your question is to compare two string logically and not as objects:

You can make use of the "===" operator which compares two operands for logical equality as well as the type of the operands.

Example:

var x="5";

x==="5" // returns true

x===5 // returns false

Refer to this: http://www.w3schools.com/js/js_comparisons.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM