0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptでページから取得した文字列をURLに反映する方法

Last updated at Posted at 2025-09-01

基本構文

history.replaceState(null, null, <URLに追加したい文字列>);

実装例

output.gif

まず、index.htmlindex.jsに以下のように記述する。

index.html

<label for="textInput">Path:</label>
<input type="text" id="textInput" />
<script src="index.js"></script>

index.js

const textInput = document.getElementById("textInput");

textInput.addEventListener("input", () => {
  const path = '/' + textInput.value;
  history.replaceState(null, null, path);
});

次に、ターミナルでindex.jsがあるディレクトリに行き、以下の好きな方でサーバーを立ち上げてアクセスすると、入力した値がURLに反映されるのが確認できる。

python

以下を実行し、localhost:8000をブラウザで開く。

python3 -m http.server 8000

npx

以下を実行して、表示されたURLを開く。

npx serve -s . -l 8000
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?