JavaScript- How do I return the character at that index without using charAt method

前端 未结 4 1440
忘掉有多难
忘掉有多难 2021-01-16 17:57

I have a function that accept two parameters string and index. How do I write a code that will return the character at that index without using javascript built in method ch

相关标签:
4条回答
  • 2021-01-16 18:37

    Can you please check this:

    $('#show').click(function(){
      var string = $('#string').html();
      var position = $('#position').val() - 1;
      var result = string[position];
      $('#result').html(result);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <span id='string'>ABCDEFGHIJKLMNOPQRSTUVWXYZ</span><br/>
    <input type='text' id='position' value='5'> = 
    <span id="result"></span>
    <br/>
    <button id='show'>DISPLAY RESULT</button>

    0 讨论(0)
  • 2021-01-16 18:38

    Something like this should work for you:

    getIndex = (str, index) => str.split('')[index];
    console.log(getIndex("foobar", 3));

    This may also be of interest:

    String.prototype.getIndex = function(idx) {
      return this.split('')[idx];
    }
    console.log("foobar".getIndex(3));

    Hope this helps,

    0 讨论(0)
  • 2021-01-16 18:38
        function getIndex(text, i) {
            return text.slice(i,i+1);
        }
    
        console.log(getIndex('great', 1));  // --> r
    
    0 讨论(0)
  • 2021-01-16 18:58

    Create the function as below:

    function getIndex(input, i) {
        return input.substring(i, i+1);
    }
    
    getIndex("great", 1)
    

    I hope that helps!

    0 讨论(0)
提交回复
热议问题