How do I replace a character at a particular index

2018-12-31 03:09发布

I have a string, let's say Hello world and I need to replace the char at index 3. How can I replace a char by specifying a index?

var str = "hello world";

I need something like

str.replaceAt(0,"h");

19条回答
浪荡孟婆
2楼-- · 2018-12-31 03:13

function dothis() {
  var x = document.getElementById("x").value;
  var index = document.getElementById("index").value;
  var text = document.getElementById("text").value;
  var arr = x.split("");
  arr.splice(index, 1, text);
  var result = arr.join("");
  document.getElementById('output').innerHTML = result;
  console.log(result);
}
dothis();
<input id="x" type="text" value="White Dog" placeholder="Enter Text" />
<input id="index" type="number" min="0"value="6" style="width:50px" placeholder="index" />
<input id="text" type="text" value="F" placeholder="New character" />
<br>
<button id="submit" onclick="dothis()">Run</button>
<p id="output"></p>

This method is good for small length strings but may be slow for larger text.

var x = "White Dog";
var arr = x.split(""); // ["W", "h", "i", "t", "e", " ", "D", "o", "g"]
arr.splice(6, 1, 'F');
var result = arr.join(""); // "White Fog"

/* 
  Here 6 is starting index and 1 is no. of array elements to remove and 
  final argument 'F' is the new character to be inserted. 
*/
查看更多
与君花间醉酒
3楼-- · 2018-12-31 03:15

I did a function that does something similar to what you ask, it checks if a character in string is in an array of not allowed characters if it is it replaces it with ''

    var validate = function(value){
        var notAllowed = [";","_",">","<","'","%","$","&","/","|",":","=","*"];
        for(var i=0; i<value.length; i++){
            if(notAllowed.indexOf(value.charAt(i)) > -1){
               value = value.replace(value.charAt(i), "");
               value = validate(value);
            }
       }
      return value;
   }
查看更多
查无此人
4楼-- · 2018-12-31 03:16
str = str.split('');
str[3] = 'h';
str = str.join('');
查看更多
像晚风撩人
5楼-- · 2018-12-31 03:16

You could try

var strArr = str.split("");

strArr[0] = 'h';

str = strArr.join("");
查看更多
长期被迫恋爱
6楼-- · 2018-12-31 03:21

One-liner using String.replace with callback (no emoji support):

// 0 - index to replace, 'f' - replacement string
'dog'.replace(/./g, (c, i) => i == 0? 'f': c)
// "fog"

Explained:

//String.replace will call the callback on each pattern match
//in this case - each character
'dog'.replace(/./g, function (character, index) {
   if (index == 0) //we want to replace the first character
     return 'f'
   return character //leaving other characters the same
})
查看更多
闭嘴吧你
7楼-- · 2018-12-31 03:24

Lets say you want to replace Kth index (0-based index) with 'Z'. You could use Regex to do this.

var re = var re = new RegExp("((.){" + K + "})((.){1})")
str.replace(re, "$1A$`");
查看更多
登录 后发表回答