算法中级:搜索和替换
- 写一个字符串的搜索与替换函数,它的返回值为完成替换后的新字符串。
- 这个函数接收的第一个参数为待替换的句子。
- 第二个参数为句中需要被替换的单词。
- 第三个参数为替换后的单词。
注意:
需要保留被替换单词首字母的大小写格式。即如果传入的第二个参数为 “Book”,第三个参数为 “dog”,那么替换后的结果应为 “Dog”
myReplace(“Let us go to the store”, “store”, “mall”)应该返回 “Let us go to the mall”。
myReplace(“He is Sleeping on the couch”, “Sleeping”, “sitting”)应该返回 “He is Sitting on the couch”。
myReplace(“This has a spellngi error”, “spellngi”, “spelling”)应该返回 “This has a spelling error”。
myReplace(“His name is Tom”, “Tom”, “john”)应该返回 “His name is John”。
myReplace(“Let us get back to more Coding”, “Coding”, “algorithms”)应该返回 “Let us get back to more Algorithms”。
方法一:
function myReplace(str, before, after) {
// Find index where before is on string
var index = str.indexOf(before);
// Check to see if the first letter is uppercase or not
if (str[index] === str[index].toUpperCase()) {
// Change the after word to be capitalized before we use it.
after = after.charAt(0).toUpperCase() + after.slice(1);
}
// Now replace the original str with the edited one.
str = str.replace(before, after);
return str;
}
方法二:
function myReplace(str, before, after) {
//Create a regular expression object
var re = new RegExp(before,"gi");
//Check whether the first letter is uppercase or not
if(/[A-Z]/.test(before[0])){
//Change the word to be capitalized
after = after.charAt(0).toUpperCase()+after.slice(1);
}
//Replace the original word with new one
var newStr = str.replace(re,after);
return newStr;
}
方法三:
function myReplace(str, before, after) {
// create a function that will change the casing of any number of letter in parameter "target"
// matching parameter "source"
function applyCasing(source, target) {
// split the source and target strings to array of letters
var targetArr = target.split("");
var sourceArr = source.split("");
// iterate through all the items of sourceArr and targetArr arrays till loop hits the end of shortest array
for (var i = 0; i < Math.min(targetArr.length, sourceArr.length); i++){
// find out the casing of every letter from sourceArr using regular expression
// if sourceArr[i] is upper case then convert targetArr[i] to upper case
if (/[A-Z]/.test(sourceArr[i])) {
targetArr[i] = targetArr[i].toUpperCase();
}
// if sourceArr[i] is not upper case then convert targetArr[i] to lower case
else targetArr[i] = targetArr[i].toLowerCase();
}
// join modified targetArr to string and return
return (targetArr.join(""));
}
// replace "before" with "after" with "before"-casing
return str.replace(before, applyCasing(before, after));
}
方法四:
// Add new method to the String object, not overriding it if one exists already
String.prototype.capitalize = String.prototype.capitalize ||
function() {
return this[0].toUpperCase() + this.slice(1);
};
const Util = (function () {
// Create utility module to hold helper functions
function textCase(str, tCase) {
// Depending if the tCase argument is passed we either set the case of the
// given string or we get it.
// Those functions can be expanded for other text cases.
if(tCase) {
return setCase(str, tCase);
} else {
return getCase(str);
}
function setCase(str, tCase) {
switch(tCase) {
case "uppercase": return str.toUpperCase();
case "lowercase": return str.toLowerCase();
case "capitalized": return str.capitalize();
default: return str;
}
}
function getCase(str) {
if (str === str.toUpperCase()) { return "uppercase"; }
if (str === str.toLowerCase()) { return "lowercase"; }
if (str === str.capitalize()) { return "capitalized"; }
return "normal";
}
}
return {
textCase
};
})();
function myReplace(str, before, after) {
const { textCase } = Util;
const regex = new RegExp(before, 'gi');
const replacingStr = textCase(after, textCase(before));
return str.replace(regex, replacingStr);
}
以上内容来源FCC
方法:
function myReplace(str, before, after) {
let arr = str.split(' ').map((i)=>{
if(i === before){
let isCapital = (/[A-Z]/).test(i.slice(0,1));
if(isCapital){
return after.slice(0,1).toUpperCase().concat(after.slice(1))
}else{
return after;
}
}else{
return i;
}
});
return arr.join(' ')
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");