简体   繁体   中英

Without using the reverse() method. How do I maintain the original string order, space and punctuation on string that was reverse?

I am able to use a for loop without using a helper method to reverse the string. But, how do I maintain the original order, space, and punctuation on the string?

Without using the reverse() helper method I am able to reverse the string but I cannot maintain the order of the words and punctuations.

 // Reverse preserving the order, punctuation without using a helper function reverseWordsPreserveOrder(words) { let reverse = ''; for (let i = words.length -1; i >= 0; i--) { reverse += words[i]; } return reverse; } console.log(reverseWordsPreserveOrder('Javascript, can be challenging.')) // output-> .gnignellahc eb nac ,tpircsavaJ 

I expect the result to be like this:

// output-> tpircsavaJ, nac eb gnignellahc.

I'd use a regular expression and a replacer function instead: match consecutive word characters with \\w+ , and in the replacer function, use your for loop to reverse the substring, and return it:

 function reverseSingleWord(word) { let reverse = ''; for (let i = word.length -1; i >= 0; i--) { reverse += word[i]; } return reverse; } const reverseWordsPreserveOrder = str => str.replace(/\\w+/g, reverseSingleWord); console.log(reverseWordsPreserveOrder('Javascript, can be challenging.')) 

If you are trying to do it manually — no reverse() of regex s, you could:

• Defined what you mean by punctuation. This can just be a set, or using an ascii range for letters, etc. But somehow you need to be able to tell letters from non letters.

• Maintain a cache of the current word because you are not reversing the whole sentence, just the words so you need to treat them individually.

With that you can loop through once with something like:

 function reverseWordsPreserveOrder(s){ // some way to know what is letter and what is punt let punct = new Set([',',' ', '.', '?']) // current word reversed let word = '' // sentence so far let sent = '' for (let l of s){ if (punct.has(l)) { sent += word + l word = '' } else { word = l + word } } sent += word return sent } console.log(reverseWordsPreserveOrder('Javascript, can be challenging.')) 

Having said this, it's probably more efficient to use a regex.

If you are only averse to reverse because you think it can't do the job, here is a more semantic version (based on @CertainPerformance's), in ES6 you can use the spread syntax ( ... ) with the word string (as strings are iterable):

 function reverseSingleWord(word) { return [...word].reverse().join(''); } const reverseWordsPreserveOrder = str => str.replace(/\\w+/g, reverseSingleWord); console.log(reverseWordsPreserveOrder('Javascript, can be challenging.')) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM