Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
7

Javascript String.replace(): undocumented feature

Explorer ,
Nov 22, 2019 Nov 22, 2019

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 🙂

TOPICS
Scripting
2.5K
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
Mar 05, 2024 Mar 05, 2024

very useful, thank you!

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Mar 05, 2024 Mar 05, 2024
LATEST
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines