Js

FreeCodeCampノート:検索と置換



Freecodecamp Notes Search



function myReplace(str, before, after) { If(before.charAt(0)=== before.charAt(0).toUpperCase()){ // If the initials of the characters with replacement are uppercase After = after.replace(after.charAt(0),after.charAt(0).toUpperCase())//Make the first letter of after str = str.replace(before,after) }else{ After = after.replace(after.charAt(0),after.charAt(0).toLowerCase())//Change the first letter of after to lowercase str = str.replace(before,after) } return str } myReplace('A quick brown fox jumped over the lazy dog', 'jumped', 'leaped')

また、私はより簡潔な書き方を見ました:

// Solution 1 function myReplace(str,before,after){ if(before[0] === before[0].toUpperCase()){ after = after[0].toUpperCase() + after.slice(1) } str = str.replace(before,after) return str } // Solution 2 function myReplace(str,before,after){ var reg = /^[A-Z]/ if(reg.text(before.charAt(0))){ after = after.charAt(0).toUpperCase() + after.slice(1) } str = str.replace(before,after) return str } Author: Do not become a trembling little meow meow meow meow meow Link: http://www.jianshu.com/p/4d72dfe478b5 Source: Short book Copyright is owned by the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

検証後、これら2つのソリューションも可能であり、Supremeはどこにでもあります。



転載:https://www.jianshu.com/p/1da5d11bb92a