मैं जानता हूँ कि यह मूर्खतापूर्ण है, लेकिन मैं आज सुबह रचनात्मक महसूस कर रहा हूँ:
'one two, one three, one four, one'
.split(' ') // array: ["one", "two,", "one", "three,", "one", "four,", "one"]
.reverse() // array: ["one", "four,", "one", "three,", "one", "two,", "one"]
.join(' ') // string: "one four, one three, one two, one"
.replace(/one/, 'finish') // string: "finish four, one three, one two, one"
.split(' ') // array: ["finish", "four,", "one", "three,", "one", "two,", "one"]
.reverse() // array: ["one", "two,", "one", "three,", "one", "four,", "finish"]
.join(' '); // final string: "one two, one three, one four, finish"
तो सच में, तुम सब करने की आवश्यकता होगी स्ट्रिंग प्रोटोटाइप को यह समारोह जोड़ने है:
String.prototype.replaceLast = function (what, replacement) {
return this.split(' ').reverse().join(' ').replace(new RegExp(what), replacement).split(' ').reverse().join(' ');
};
फिर तो जैसे यह चलाएँ: str = str.replaceLast('one', 'finish');
एक सीमा आपको पता होना चाहिए यह है कि, के बाद से समारोह अंतरिक्ष से बंटवारे है, तो आप
शायद किसी स्थान के साथ कुछ भी नहीं ढूंढ/प्रतिस्थापित नहीं कर सकता है।
असल में, अब जब मैं इसके बारे में सोचता हूं, तो आप खाली टोकन के साथ विभाजित करके 'स्पेस' समस्या के आसपास हो सकते हैं।
String.prototype.reverse = function() {
return this.split('').reverse().join('');
};
String.prototype.replaceLast = function (what, replacement) {
return this.reverse().replace(new RegExp(what.reverse()), replacement.reverse()).reverse();
};
str = str.replaceLast('one', 'finish');
अच्छा विचार। पहले उस स्ट्रिंग से बचने की आवश्यकता है (हालांकि उसके नमूना डेटा के साथ नहीं, दिया गया है), जो गैर-तुच्छ है। ! :-( –
आप बहुत ज्यादा – Ruth
@Ruth कोई समस्या @TJ हाँ, वास्तव में यह सच है धन्यवाद: रुथ यदि आप के साथ "शब्द" आप देख रहे हैं कि के लिए नियमित अभिव्यक्ति के लिए इस्तेमाल किया विशेष वर्ण शामिल अंत, आप आवश्यकता होगी कोशिश @SuperUberDuper 'str.replace (नई RegExp उन है, जो के रूप में टीजे कहते हैं (हालांकि नहीं असंभव) एक छोटे से मुश्किल है" पलायन "के लिए। – Pointy