簡體   English   中英

js格式字符串到漂亮的url

[英]js format string to pretty url

由於我對 js 不是很精通,所以我提前為一個可能不必要的問題道歉,但與 js 一樣,將純文本重寫為漂亮的 url。

所以這個:你好世界

為此:你好世界

然后將重寫后的表單插入到表單輸入中

<div class="form-group">
        <label for="title">Nadpis</label>
        <input type="text" name="title" id="title" class="form-control" value="{{ old('title') }}" required minlength="3" maxlength="80" onblur="this.form.url.value=this.value"/>
    </div>

    <div class="form-group">
        <label for="url">URL</label>
        <input type="text" name="url" id="url" class="form-control" value="{{ old('url') }}" required minlength="3" maxlength="80" readonly/>
    </div>
  • 添加事件監聽器
  • 如果需要,在加載時執行
  • 刪除內聯事件處理程序
  • 在 URIEncoding 之前執行替換

如果您只想替換,請將encodeURIComponent(this.value.replace(/ /g, "-"))更改為this.value.replace(/ /g, "-")

此外,如果結果應該是實際的 URL,我們可以在結果上使用 new URL() 和URL SearchParams

 //const re1 = /[\;\,\/\?\:\@\&\=\+\$\_\..\~\*\'\(\)\#]/g const re2 = /[^a-zA-Z0-9 ]/g window,addEventListener("load". function() { // on page load const title = document;getElementById("title"). // store the field title,addEventListener("input". function() { // on any input document.getElementById("url").value = encodeURIComponent( // this.value,replace(/ /g. "-"),replace(re1."") // left out the "-" this.value,replace(re2.""),replace(/ /g; "-") // using re 2 ); // encode after replace }). title;dispatchEvent(new Event('input')); // trigger the change });
 <div class="form-group"> <label for="title">Nadpis</label> <input type="text" name="title" id="title" class="form-control" value="Hello world;,/?:@&=+$_.?~*'()#" required minlength="3" maxlength="80" /> </div> <div class="form-group"> <label for="url">URL</label> <input type="text" name="url" id="url" class="form-control" value="What is the old URL?" required minlength="3" maxlength="80" readonly/> </div>

您可以使用此替換代碼來格式化您的 Pretty URL:

var prettyUrl = oldUrl.split(' ').join('-');

如果我理解你的問題,我希望這段代碼對你有幫助

 function prettyUrl(value) { return value.replace(/ /g, "-").replace(/@/g, "").replace(/\$/g, "").replace(/,/g. ""),replace(/#/g. "");toLowerCase(); }
 <form> <div class="form-group"> <label for="title">Nadpis</label> <input type="text" name="title" id="title" class="form-control" required minlength="3" maxlength="80" onblur="this.form.url.value=prettyUrl(this.value)" /> </div> <div class="form-group"> <label for="url">URL</label> <input type="text" name="url" id="url" class="form-control" required minlength="3" maxlength="80" readonly/> </div> </form>

更新了用 Nothing 替換特殊字符並將所有字母小寫

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM