Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

searc and replace fcc solution

function myReplace(str, before, after) {
  let regExp = /^[A-Z]/; // checks if a word starts with capital letter
  
  let replaceIndex = str.toLowerCase().split(' ').indexOf(before.toLowerCase());
  //replace index splits the string and returns the index of the word to be replaced
  if(regExp.test(str.split(' ')[replaceIndex])){
    return str.replace(new RegExp(`${before}`, 'i'), after.replace(after.charAt(0), after.charAt(0).toUpperCase()))
    // this checks if the word to be replaced (before) starts with a capital letter and changes the first letter
    //and changes the first letter of the replacement word (after) to uppercase if it is true
    // it then replaces the word to be replaced (before) with our new replacement word (after) that has an
    // first letter
  }else{
    return str.replace(new RegExp(`${before}`, 'i'), after.replace(after.charAt(0), after.charAt(0).toLowerCase()))
    // if the first condition returned false, this converts the first letter of the replacement word (after)
    // to lowercase and then replaces the word to be replaced (before) with our new replacement word (after)
    // that has it's first letter now in lowercase
  }
}

console.log(myReplace("He is sleeping on the couch", "Sleeping", "Sitting")); // he is sitting on the couch
console.log(myReplace("He is Sleeping on the couch", "Sleeping", "sitting")); // he is Sitting on the couch
Comment

PREVIOUS NEXT
Code Example
Javascript :: array.push multiple 
Javascript :: how to deploy firebase angular 10 
Javascript :: vue style 
Javascript :: how to append in javascript 
Javascript :: window location 
Javascript :: appearing datepicker behind the modal 
Javascript :: how copy url of page to clipboard javascript 
Javascript :: how to get MathJax 
Javascript :: using datatable 
Javascript :: how to compare previous value with current in jquery 
Javascript :: js exclude from object 
Javascript :: node settimeout 
Javascript :: sort list of objects by value node js 
Javascript :: javascript concat 
Javascript :: react router switch 
Javascript :: chrome extension onclick not working 
Javascript :: count occurence in array js 
Javascript :: copia array javascript 
Javascript :: find intersection between two object arrays javascript 
Javascript :: ?? in javascript 
Javascript :: javascript this 
Javascript :: address format json 
Javascript :: how to add an event listener to a function javascript 
Javascript :: express mysql sessions 
Javascript :: react hook form password validation uppercase 
Javascript :: object literal js 
Javascript :: how to add array object in javascript 
Javascript :: check if an input element has focus 
Javascript :: bind method in javascript 
Javascript :: multi key cookie js 
ADD CONTENT
Topic
Content
Source link
Name
2+5 =