• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Forum
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Replace a portion of a string with something else

Replace a portion of a string with something else

Replace a portion of a string with something else

The replace() method accepts two arguments: the string to find, and the string to replace it with.

var text = 'I love Cape Cod potato chips!';

// returns "I love Lays potato chips!"
text.replace('Cape Cod', 'Lays');

By default, the replace() method replaces the first match. To replace all matches, you’ll need to pass in a regular expression with the global flag (g).

var chips = 'Cape Cod potato chips are my favorite brand of chips.';

// Only replaces the first instance of the word "chips"
chips.replace('chips', 'deep fried potato slices');

// Replaces all instances of the word "chips"
chips.replace(new RegExp('chips', 'g'), 'deep fried potato slices');

Source

https://vanillajstoolkit.com/reference/strings/string-replace/

Miscellaneous

Related Snippets:

  • Press shift and enter for a new line
  • Aliases with JavaScript Destructuring
  • Add special characters to text to print in color in the console
  • Check if an Object Is Empty

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2022 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us