3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javascriptでurlのパスを取得

Last updated at Posted at 2019-09-07

概要

javascriptでurlの文字列からパスの文字列を取得したい。
'http://localhost:3000/hoge/huga'
の場合は'hoge/huga'の部分
'http://localhost:3000/'
の場合は'/'を取得したい

splitしてsliceしてjoinする


// 'http://localhost:3000/hoge/huga'.split('/').slice(3)
// →["hoge","huga"]
let path = 'http://localhost:3000/hoge/huga'.split('/').slice(3).join('/')
path == '' ? '/' : path
// →"hoge/huga"

// 'http://localhost:3000/'.split('/').slice(3)
// →[""]
path = 'http://localhost:3000/'.split('/').slice(3).join('/')
path == '' ? '/' : path
// →"/"

splitしてsliceして+=演算子を使う


let path_list = 'http://localhost:3000/hoge/huga'.split('/').slice(3)
let path = ''
for(let v of path_list){
  path += (v == '') ? '/' : v
}
// →"hoge/huga"

path_list = 'http://localhost:3000/'.split('/').slice(3)
path = ''
for(let v of path_list){
  path += (v == '') ? '/' : v
}
// →"/"

不完全燃焼

  • 三項演算子使わない方がいい?もう少しシンプルにしたい。replace使えばシンプルにいけそうだけど、正規表現が分からぬ…
  • Javascript側、もしくはライブラリなんかでurl扱うメソッドとかない?

ちなみにrubyの場合、URI.splitを使う


require 'uri'
URI.split('http://localhost:3000/')
=> ["http", nil, "localhost", "3000", nil, "/", nil, nil, nil]
index urlの要素
0 scheme
1 userinfo
2 host
3 port
4 registry
5 path
6 opaque
7 query
8 fragment
3
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?