www.webdeveloper.com
Results 1 to 4 of 4

Thread: how to replace a string by specifying position in javascript?

  1. #1
    Join Date
    Nov 2011
    Posts
    22

    how to replace a string by specifying position in javascript?

    i have a string with value as shown below.

    var node="1.1.1"

    i need to replace a character by specifying the position.
    For eg:- i need to replace the last one with 2

    any help?

  2. #2
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,350

    Lightbulb

    See if you can figure out how this works for you...
    Code:
    <script type="text/javascript">
    
    String.prototype.replaceAt = function () {
        var rlen = arguments[2] == null ? 1 : arguments[2];
        return this.substring(0, arguments[0]) + arguments[1] + this.substring(arguments[0] + rlen);
    }
    
      str = '1.1.1';
      str += '\n'+str.replaceAt(4,'2');
      alert(str);
    </script>

  3. #3
    Join Date
    Feb 2012
    Posts
    218
    Or equally
    Code:
    <script type="text/javascript">
    	function replaceStr(str, pos, value){
    		var arr = str.split('');
    		arr[pos]=value;
    		return arr.join('');
    	}
    	str = '1.1.1';
    	alert( replaceStr(str, 4, '2') )
    </script>

  4. #4
    Join Date
    Nov 2011
    Posts
    22
    thanks...it worked...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles