JavaScript replace() behaves differently on desktop and online

marc_renault shared this problem 8 months ago
Solved

In GGB 5 (desktop), I used the JavaScript command s = s.replace(" ", "") to remove the first space in string s. Unexpectedly, it acted globally, removing ALL the spaces from string s. When I uploaded the applet, the online version worked as expected, only removing the first space. (JavaScript documentation says this should not act globally.)

Compare the attached file with its uploaded version: https://www.geogebra.org/m/jbkzbhpq.

Thanks!

Comments (8)

photo
1

Does this work?

"jhgj jh jjh jh".replace(/\s+/,"")

photo
1

No. In GGB 5.0.570.0-d (Windows 10), that does NOT work. I get an error, attached. (I tried other regular expressions, too, but GGB always gives me an error.)

However, when I upload the file to geogebra.org, then that line of JavaScript DOES work online as expected. https://www.geogebra.org/ma...

photo
photo
1

Please check you are using a current version, 'xabyabzab'.replace('ab', 'c') works fine for me in Classic 5 (gives xcyabzab)

photo
1

Weird. Yes, replace() gives the correct result for string literals, but not for variables. For example, these lines of code

ggbApplet.setTextValue("txt", "a b c d e")
var s = ggbApplet.getValueString("txt")
s = s.replace(" ", "")
ggbApplet.setTextValue("txtResult", s)

produce the value "abcde". But if I change only the third line,

ggbApplet.setTextValue("txt", "a b c d e")
var s = ggbApplet.getValueString("txt")
s = "a b c d e".replace(" ", "")
ggbApplet.setTextValue("txtResult", s)
then it produces "ab c d e".

photo
1

Does it work if you change it to

var s = ggbApplet.getValueString("txt")+""

photo
1

... because

alert(typeof ggbApplet.getValueString("txt"))
alert(typeof (ggbApplet.getValueString("txt")+""))

photo
1

Yep - that did the trick. Once I coerce s to a string (from an object) then the replace function behaves as it should. Thanks for suggesting the alert messages.

Marc

photo
1

Thanks, added to manual https://wiki.geogebra.org/s...

photo
© 2020 International GeoGebra Institute