Wednesday, December 26, 2012

Jquery, Javascript – .replace is not a function

Basically, I wanted replace some part of a string then trim white space from the beginning and end of a string. The standard answer on the internet is as follows:

var text = "asd (Some text)";
var txt = text.match(/([a-zA-Z0-9 ]*)/g);
txt = txt.replace("text", '');
txt = $.trim(txt);

I eventually realized that “.replace” is only a function when the operand is a string; in my case, selectedtext was an object, and therefore I needed to cast it to a string, as follows:

txt = txt.toString().replace("text", '');

This then gave me the correct result.

No comments:

Post a Comment