Skip to main content
Known Participant
November 22, 2019
Question

Javascript String.replace(): undocumented feature

  • November 22, 2019
  • 2 replies
  • 2821 views

ESTK object model viewer describes string.replace() function as following:

String.replace (what: any, with: string):

string Core JavaScript Classes

what: Data Type: any

with: Data Type: string

 

But as you probably know, this function doesn't replace all occurences in a string.

 

var s = 'old old old';
var ss = s.replace('old', 'new');
$.writeln(ss);

 

Result: new old old

 

Therefore I have always used a regular expression with 'g' flag as 1st argument to replace all occurences in a string:

 

var s = 'old old old';
var sss = s.replace(/old/g, 'new');
$.writeln(sss);

 

Result: new new new

 

But as I discovered recently, we can still use the default syntax if we use regular expression flag(s) as third argument:

 

var s = 'old old old';
var ssss = s.replace('old', 'new', 'g');
$.writeln(ssss);

 

Result: new new new

 

Maybe someone will find it useful 🙂

This topic has been closed for replies.

2 replies

Robert at ID-Tasker
Legend
March 5, 2024
Participating Frequently
March 5, 2024

very useful, thank you!