treckstar

Performs multiple replacements on a single string - Example

May 25th, 2023
1,058
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 1.17 KB | Source Code | 0 0
  1. /**
  2. * fn: https://pastebin.com/WzcVWLU1
  3. * This function takes two parameters:
  4. *
  5. * str - The original string in which the replacements will be performed.
  6. * replacements - An array of tuples, where each tuple contains the search
  7. * text and its corresponding replacement text.
  8. * The function iterates over each tuple in the replacements array.
  9. * For each tuple, it calls the replace method on the result string,
  10. * replacing all occurrences of the search text with the replacement
  11. * text using a regular expression with the 'g' flag for global search.
  12. *
  13. * The resulting modified string is returned from the function.
  14. *
  15. **/
  16.  
  17. const originalString = 'Hello, world! Hello, universe!';
  18. const replacements: [string, string][] = [
  19.   ['Hello', 'Hi'],
  20.   ['world', 'earth']
  21. ];
  22.  
  23. const modifiedString = replaceMultipleValues(originalString, replacements);
  24.  
  25. console.log(modifiedString); // Hi, earth! Hi, universe!
  26.  
  27. /**
  28. * Output: Hi, earth! Hi, universe!
  29. *
  30. * In this example, the original string 'Hello, world! Hello, universe!'
  31. * is modified by replacing "Hello" with "Hi" and "world" with "earth",
  32. * resulting in the modified string 'Hi, earth! Hi, universe!'.
  33. **/
  34.  
  35.  
  36.  
Advertisement
Add Comment
Please, Sign In to add comment