How do I replace a character at a particular index in JavaScript?

后端 未结 24 2114
孤城傲影
孤城傲影 2020-11-21 07:23

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 = \"h         


        
相关标签:
24条回答
  • 2020-11-21 08:13

    function dothis() {
      var x = document.getElementById("x").value;
      var index = document.getElementById("index").value;
      var text = document.getElementById("text").value;
      var length = document.getElementById("length").value;
      var arr = x.split("");
      arr.splice(index, length, 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="length" type="number" min="0"value="1" style="width:50px" placeholder="length" />
    <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');
    
    /* 
      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. 
    */
    var result = arr.join(""); // "White Fog"
    
    0 讨论(0)
  • 2020-11-21 08:13

    this is easily achievable with RegExp!

    const str = 'Hello RegEx!';
    const index = 11;
    const replaceWith = 'p';
    
    //'Hello RegEx!'.replace(/^(.{11})(.)/, `$1p`);
    str.replace(new RegExp(`^(.{${ index }})(.)`), `$1${ replaceWith }`);
    
    //< "Hello RegExp"
    
    0 讨论(0)
  • 2020-11-21 08:13

    The methods on here are complicated. I would do it this way:

    var myString = "this is my string";
    myString = myString.replace(myString.charAt(number goes here), "insert replacement here");
    

    This is as simple as it gets.

    0 讨论(0)
  • 2020-11-21 08:15

    Here is a version I came up with if you want to style words or individual characters at their index in react/javascript.

    replaceAt( yourArrayOfIndexes, yourString/orArrayOfStrings ) 
    

    Working example: https://codesandbox.io/s/ov7zxp9mjq

    function replaceAt(indexArray, [...string]) {
        const replaceValue = i => string[i] = <b>{string[i]}</b>;
        indexArray.forEach(replaceValue);
        return string;
    }
    

    And here is another alternate method

    function replaceAt(indexArray, [...string]) {
        const startTag = '<b>';
        const endTag = '</b>';
        const tagLetter = i => string.splice(i, 1, startTag + string[i] + endTag);
        indexArray.forEach(tagLetter);
        return string.join('');
    }
    

    And another...

    function replaceAt(indexArray, [...string]) {
        for (let i = 0; i < indexArray.length; i++) {
            string = Object.assign(string, {
              [indexArray[i]]: <b>{string[indexArray[i]]}</b>
            });
        }
        return string;
    }
    
    0 讨论(0)
  • 2020-11-21 08:17
    str = str.split('');
    str[3] = 'h';
    str = str.join('');
    
    0 讨论(0)
  • 2020-11-21 08:18

    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;
       }
    
    0 讨论(0)
提交回复
热议问题