Nodejs String Splice splice(idx, rem, s)

Here you can find the source of splice(idx, rem, s)

Method Source Code

//Problem 5. nbsp
//Write a function that replaces non breaking white-spaces in a text with &nbsp ;

String.prototype.splice = function (idx, rem, s) {
    return (this.slice(0, idx) + s + this.slice(idx + Math.abs(rem)));
};

function replaceWhiteSpace(text) {
    return (text.split(' ').join(' '));
}

//onother possible solution
function replaceWhiteSpace2(text){
    var i, /*  w w  w.j  a  v a 2s .  co  m*/
        possitions = [];

    for (i = 0; i < text.length; i += 1) {
        if (text[i] === ' ') {
            possitions.push(i);
        }
    }

    for (i = possitions.length - 1; i >= 0; i -= 1) {
        
        text = text.splice(possitions[i], -1, '&nbsp');
    }

    return text;
}


//tests

var text = "We are living in an yellow submarine. We don't have anything else. inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.";

console.log('Original text: \n' + text);
console.log();
console.log('After raplacing all white spaces: \n' + replaceWhiteSpace(text));

Related

  1. splice( idx, rem, s )
    String.prototype.splice = function( idx, rem, s ) {
        return (this.slice(0,idx) + s + this.slice(idx + Math.abs(rem)));
    };
    
  2. splice( idx, rem, s )
    String.prototype.splice = function( idx, rem, s ) {
        return (this.slice(0,idx) + s + this.slice(idx + Math.abs(rem)));
    };
    
  3. splice( idx, rem, s )
    String.prototype.splice = function ( idx, rem, s ) {
      return ( this.slice( 0, idx ) + s + this.slice( idx + Math.abs( rem ) ) );
    
  4. splice(...args)
    String.prototype.splice = function(...args) {
      var x = this.split("");
      x.splice(...args);
      return x.join("");
    };
    
  5. splice(addedStr, index)
    String.prototype.splice = function(addedStr, index){
     var substr = this.slice(0, index)
     var rest = this.slice(index, this.length)
     return substr + addedStr + rest;
    
  6. splice(idx, rem, str)
    String.prototype.splice = function(idx, rem, str) {
        return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
    };
    module.exports = String.splice;
    
  7. splice(index, count=0, add='')
    String.prototype.splice = function(index, count=0, add='') {
      while (index < 0) { index += this.length || (index*-1); }
      return this.slice(0, index) + add + this.slice(index + count);
    
  8. splice(start, length, replacement)
    String.prototype.splice = function(start, length, replacement) {
        return this.substr(0, start) + replacement + this.substr(start + length);
    };