Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to solve a problem in JavaScript. I have a string text consisting of English word. I need to find all the capital and lowercase F's in a word and need to insert T in front of that word. Please help me! Thank you.


What I have tried:

function addTbeforeFs(text, chr) {
  var output = '';
  for (var i = 0; i < text.length; i++) {
    if (i % 3 === 0) output += chr;
    output += text.charAt(i);
  }

  return output;
}

alert(addTbeforeFs('Fluffy', 'T'));

//My Output is : TFluTffy

// Expected Output should be: TFluTfTfy
Posted
Updated 26-Mar-20 7:39am
Comments
phil.o 26-Mar-20 13:23pm    
Why do you insert chr every three characters instead of testing for the current value and act accordingly? i % 3 === 0 will not test whether current letter is an upper or lower-case F.
Member 14783910 26-Mar-20 13:31pm    
I am new to JS, i am trying to figure it out how to get the expected output... I am thinking to apply RegExp but don't know where to start... and yes what i did over there may be it is the wrong way to approach the solution. Thank you!
phil.o 26-Mar-20 14:01pm    
You should try to do it without a regular expression first; you should learn to do it the iterative way, because that's the point of the exercise: iterate a string, test for a given condition, and act accordingly.
Begin by drawing a diagram on a piece of paper, then translate that into code.

1 solution

Regular expressions would be the easiest option:
JavaScript
function addLetterBeforeFs(text, letterToAdd) {
    return text.replace(/f/gi, letterToAdd + "$&");
}
Regular expressions - JavaScript | MDN[^]
String.prototype.replace() - JavaScript | MDN[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900