Search code examples
vimneovim

how to get the word between two character in vim script?


My cursor is on the word <header>.

If I run the function expand("<cword>") it will return for me the word <header> I want get only what is between <> which is header.

I want to write a function that takes three arguments

foo(string, startChar, endChar)

and returns the characters between startChar and endChar.

Could you help please ?


Solution

  • After researching an answer I found one. The answer is that by default the expand('<cword>') return the word between special character such as '<' or '' ... but if I want to get the groups of characters between two indexes we can write a function that do the job

    function Get_string_between(string, start, end)
      let str=""
      "get length of string
      let len =strlen(a:string)
    
      "set the default values o start and end indexes to 0
      let startIndex=0
      let endIndex=0
    
    
    "Get the index of start and end characters
      let i =0
      while i < len
        if a:string[i]  == a:start && startIndex == 0
          let startIndex =i
        elseif a:string[i] == a:end && endIndex == 0
          let endIndex =i
        endif
        let i += 1
      endwhile
      echo "StartIndex: ". startIndex
      echo "endIndex: ". endIndex
    
      let i =startIndex+1
    
      while i < endIndex
        let str .= a:string[i]
        let i +=1
      endwhile
      return str
    endfunction