Hatena::Groupvim

encodeURI()/encodeURIComponent()

encodeURI()/encodeURIComponent()

JavaScriptのアレ

function! s:char2hex(c)
  if a:c =~# '^[:cntrl:]$' | return '' | endif
  let r = ''
  for i in range(strlen(a:c))
    let r .= printf('%%%02X', char2nr(a:c[i]))
  endfor
  return r
endfunction

function! s:encodeURI(s)
  return substitute(a:s, '[^0-9A-Za-z-._~!''()*#$&+,/:;=?@]',
        \ '\=s:char2hex(submatch(0))', 'g')
endfunction

function! s:encodeURIComponent(s)
  return substitute(a:s, '[^0-9A-Za-z-._~!''()*]',
        \ '\=s:char2hex(submatch(0))', 'g')
endfunction

一行版 encodeURI()/encodeURIComponent() 。制御文字をはじいていない問題がある。

" TODO: 制御文字をはじく

function! s:encodeURI(s)
  return substitute(a:s, '[^0-9A-Za-z-._~!''()*#$&+,/:;=?@]', '\=join(map(range(strlen(submatch(0))), ''printf("%%%02X", char2nr(submatch(0)[v:val]))''), "")', 'g')
endfunction

function! s:encodeURIComponent(s)
	return substitute(a:s, '[^0-9A-Za-z-._~!''()*]', '\=join(map(range(strlen(submatch(0))), ''printf("%%%02X", char2nr(submatch(0)[v:val]))''), "")', 'g')
endfunction