Click here to Skip to main content
14,486,686 members
Rate this:
Please Sign up or sign in to vote.
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
Updated 4 days ago
phil.o 4 days ago
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 4 days ago
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 4 days ago
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

Rate this:
Please Sign up or sign in to vote.

Solution 1

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

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

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100