简体   繁体   中英

include prototype function globally (react)

I have the following function to quickly replace words in a string (with multiple occurences):

String.prototype.replaceAll = function (search, replacement) {
  var target = this;
  return target.replace(new RegExp(search, 'g'), replacement);
};

This function works as expected. I need this function in multiple components (files) and functions, so I add this function directly at the beginning of every file. Is there an easy solution to include this kind of functions globally to a project without adding it separately to every file?

Edit:

// strings.js
import React from 'react';
String.prototype.replaceAll = function (search, replacement) {
  var target = this;
  return target.replace(new RegExp(search, 'g'), replacement);
};

Should I export this function or how can I import this function? Can I add import strings.js at the top of App.js?

If you modify the string prototype, your work is done. The function will be available everywhere immediately. However, you should be aware that modifying the prototype of types like String is frowned upon: https://flaviocopes.com/javascript-why-not-modify-object-prototype/

Also, if you are using TypeScript, you won't see the new function without casting the string to some type of your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM