0

How can i replace prototype and make the same code below to work? in other words i wanna write a code with the same meaning/logic without using prototype.

String.prototype.replaceAt = function(index, character) {
    return this.substr(0, index) + character + 
        this.substr(index + character.length);              
}
4
  • 4
    You can simply define it as a function/method of an object. Commented Nov 23, 2013 at 4:44
  • Mr.Ahmed i tried to implement your method, but it's not working for some reason. is it possible to make a separate function that can do the same job. my only problem is, i cant show all my project publicly. is it possible to communicate with u privately? Commented Nov 23, 2013 at 7:09
  • Can you show me how you are defining and using it? There might be something wrong there...... Commented Nov 23, 2013 at 9:53
  • am using it for a spellchecker program. in-line function to replace character in a string. Commented Nov 23, 2013 at 16:45

2 Answers 2

1

Create it as a method of a custom utility object -

var StringUtils = {};

StringUtils.replaceAt = function (str, index, character) {
    return str.substr(0, index) + character + 
        str.substr(index + character.length);
}

and then call it like this -

var str = "Hello";
StringUtils.replaceAt(str, 0, "A");
Sign up to request clarification or add additional context in comments.

Comments

0

You can just define it as a function and use the call or apply prototype method

replaceAt = function(index, character) {
  return this.substr(0, index) + character + this.substr(index+character.length);
}

How to use?

var str = "Javascript is Awesome";
replaceAt.call(str, 0, "A");
// or 
replaceAt.apply(str, [0, "A"]);

2 Comments

You see, it's not a good idea to force the use of apply/call by using this inside the function. It's not intuitive and hence can create hard-to-find bugs.
@SayemAhmed True, I was not sure how extreme the questioner was about "same meaning/logic". Your method is how I would probably do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.