Table of Contents
Introduction
हेलो दोस्तों आज हम इस post में javascript के replace() और replaceAll() method के बारेमे जानेगे!.
javascript में इन दोनों method का इस्तेमाल string में substring को किसी new string के साथ replace करने
के लिए किया जाता है!.
replace() method
replace() method दिए गए string में specified substring के साथ replace करती है!. replace() method में
दिए गई substring string में first substring match होने वाली को ही replace करती है!.
replace() method के दो arguments होते है!. पहला argument string में जिस substring को replace करना है वह
और दूसरे argument में string जिस substring को add करना है!.
Example:
<script> let str = "I like apples and oranges."; let newStr = str.replace("apples", "bananas"); console.log(newStr); // "I like bananas and oranges." </script>
ऊपर के example में देख सकते है replace() method string में “apples” को “bananas” से replace किया है!.
replaceAll() method
replaceAll() method दिए गई string में specified substring के साथ string में match होने वाली सभी string को replace कर देता है!.
Example:
<script> let str = "I like apples and apples."; let newStr = str.replaceAll("apples", "bananas"); console.log(newStr); // "I like bananas and bananas." <script>
ऊपर के example में देख सकते है replaceAll() method string में “apples” की सभी substring को “bananas” से
replace कर दिया है!.
replaceAll() method ECMAScript 2021 में introduced किया गया था और वह javascript के पुराने version में supported
able नहीं है!. अगर आपको javascript के पुराने version में support करने की जरूरियात है तो आप global flag(/g) के साथ इस्तेमाल कर सकते है!.
Example:
<script> let str = "I like apples and apples."; let newStr = str.replace(/apples/g, "bananas"); console.log(newStr); // "I like bananas and bananas." </script>