मान लें कि निम्नलिखित हमारी स्ट्रिंग है -
var sentence = 'My Name is John, Smith I live in US';
console.log("The original value="+sentence); हमें अल्पविराम और निम्नलिखित शब्द के बाद के पाठ को हटाने की जरूरत है यानी "मैं अमेरिका में रहता हूं" को हटाने और बाकी को रखने के बाद। यह परिणामी स्ट्रिंग होगी -
My Name is John, Smith
इसके लिए स्प्लिट () के साथ मैच () का इस्तेमाल करें।
उदाहरण
var sentence = 'My Name is John, Smith I live in US';
console.log("The original value="+sentence);
var expression = sentence.match(/([^,]*)(.*)/)[1];
var positionForComma = sentence.match(/([^,]*),(.*)/)[2].split(' ')[1]
var newValue = expression + ', ' + positionForComma
console.log("Updated="+newValue); उपरोक्त प्रोग्राम को चलाने के लिए, आपको निम्न कमांड का उपयोग करने की आवश्यकता है -
node fileName.js.
यहाँ, मेरी फ़ाइल का नाम है demo175.js.
आउटपुट
यह निम्नलिखित आउटपुट देगा -
PS C:\Users\Amit\javascript-code> node demo175.js The original value=My Name is John, Smith I live in US Updated=My Name is John, Smith