Nodejs String Replace replace(index, subString)

Here you can find the source of replace(index, subString)

Method Source Code

//Write a function that replaces non breaking white-spaces in a text with  

var text = '',
    inputMessage = 'Enter a text:',
    replacedText,//from w  w  w.j av a  2s  .c o m
    nonBreakingWhiteSpace = '&nbsp';

String.prototype.replace = function (index, subString) {
    var replacedText = this.substr(0, index) + subString + this.substr(index + 1);
    return replacedText;
}

function replaceNonBreakingWhiteSpaces(text) {
    var i;
    for (i = 0; i < text.length - 1; i += 1) {
        if (text[i] === ' ') {
            while (text[i + 1] === ' ') {
                text = text.replace(i + 1, nonBreakingWhiteSpace);
                i += nonBreakingWhiteSpace.length;
            }
        }
    }

    return text;
}

text = prompt(inputMessage);
replacedText = replaceNonBreakingWhiteSpaces(text);
console.log(replacedText);

Related

  1. replaceAt(index, replacement)
    String.prototype.replaceAt=function(index, replacement) {
        return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
    
  2. replaceAt(index, stringInserted)
    String.prototype.replaceAt = function(index, stringInserted) {
        return this.substr(0, index) + stringInserted + this.substr(index+stringInserted.length);
    };
    
  3. replaceAt(index, text)
    String.prototype.replaceAt = function(index, text){
        return this.substr(0, index) + text + this.substr(index + text.length);
    
  4. replaceAt(index, value)
    String.prototype.replaceAt = function(index, value) {
        var str1 = this.slice(0, index);
        var str2 = this.slice(index+1);
        return str1 + value + str2;
    };
    
  5. replaceAt(startIndex, endIndex, value)
    String.prototype.replaceAt = function(startIndex, endIndex, value) {
      var beforeIndex = this.substr(0, startIndex);
      var afterIndex = this.substr(endIndex);
      return beforeIndex + value + afterIndex;
    };
    
  6. replaceAt_with_size(index, text, size)
    String.prototype.replaceAt_with_size = function(index, text, size){
        return this.substr(0, index) + text + this.substr(index + size);
    
  7. replaceBorderWidth(width)
    String.prototype.replaceBorderWidth = function(width) {
      if ( ! width) width = 1;
      return this.replace(/^[0-9]+([a-z]+)?( [a-zA-Z]+ .+)$/, width+'px$2');
    };
    
  8. replaceChars(character, replacement)
    String.prototype.replaceChars = function(character, replacement){
        var str = this;
        var a;
        var b;
        for(var i=0; i < str.length; i++){
            if(str.charAt(i) == character){
                a = str.substr(0, i) + replacement;
                b = str.substr(i + 1);
                str = a + b;
    ...
    
  9. replaceDateFormat()
    String.prototype.replaceDateFormat=function(){
        return this.replace(/-/g,'/');