Very new to Js. Trying to replace a character in a symbol.

geddonn's icon

Hi guys,

I'm very new to js and am having a bit of trouble implementing a function.

Basically the code is supposed to retrieve the patcher name and filepath
and then to filter out spaces and replace them with "!"

I've got the first part down but the second part is giving me trouble.

I searched for character replacing in javascript and came across the command "str.replace(/ /g,"!");
but it doesn't seem to be working the way I expected it to.

I've also looked at the regexp in js patch in the examples folder but it was a bit complicated for me at this point.

Heres my code so far:

outlets = 1;
setinletassist(0,"symbolIn");
setoutletassist(0,"replace space with !");

function bang()
    {
        var str =(this.patcher.name, this.patcher.filepath);
        str.replace(/ /g,"!");
        outlet(0, str);
    }

David Butler's icon

Two errors here:

1. I presume you want to join the patter name and patcher file path into one string? You can use the "+" operator in javascript to join strings. However, this will join the strings straight after one another, so we also should include a space.

var str = this.patcher.name + " " + this.patcher.filepath;

2. Replace is a function which produces a result. It does not change the value of str. In order to update str with the new value, you need to assign it:

str = str.replace(" ", "!");

geddonn's icon

thanks so much for this. very very helpful to a newcomer.
Although I found a problem.
The space is replaced between the patcher name and file path, although spaces within the file path are still there.

So if patcher name is "foo" and file path is "User/Max 6 Projects/"
I get: "foo!User/Max 6 Projects/"
rather than "foo!User/Max!6!Projects/"

Do the modifications you made only change the first space in the string?

Thanks again!