views:

75

answers:

2

Let's say hypothetically I want to replace all 'a' in a string with 'b'

'abc' -> 'bbc'

I want to run this on various strings:

var str1= 'abc'
var str2= 'adf'
var str3= 'abvxvb'
var str4= 'ae54'

I'm trying to write a jquery plugin that does this.

So I can do str1.a_to_b(); and get the desired result. (Actually having the syntax in another form is fine too).

There's something wrong with my attempted syntax:

jQuery.fn.a_to_b = function(expr) {
    return this.each(function() {
     this = this
     .replace(/a/ig, "b");
    });
};

Thanks.

+4  A: 

jQuery methods (attached to jQuery.fn) work with html elements, not strings. You want a static function (which you attach to jQuery itself)

jQuery.aToB = function(str) {
   return str.replace(/a/g, "b");
}

alert($.aToB("abc"))

Alternatively you can extend String.prototype (not recommended, since this is a potential conflict source)

String.prototype.toB = function() {
   return this.replace(/a/g, "b");
}

alert("abc".toB())
stereofrog
A: 

With a different sintax, maybe you can use the following

jQuery.a_to_b = function(str) {
    return str.replace(/a/ig, "b");
};

And after that you could call

var str1= 'abc';

str1 = jQuery.a_to_b(str1);

and you would have the new value stored in str1

xavivars