简体   繁体   中英

Replace special characters in two fields with javascript

I have a form to add a field with news title and would like to use this field to add to the title of the url.
I would like to rewrite the title live in another field like this:

http://jsfiddle.net/atmoner/5sPZa/1/

but I would replace the special character (space, interrogation, exclamation ....)
Even if they should be written in plain, it does not bother me, but I do not see how

Exemple:

new article,like this !

To:

new-article-like-this

You can change this:

$("#label2").val(this.value);

to this:

var value = this.value;
value = value.replace(/[^a-zA-Z0-9]+/g, '-');  // special char(s) -> hyphen
value = value.replace(/^-|-$/g, ''); // remove leading/trailing hyphen
$("#label2").val(value);

Try below code.. It is just a starting point.. customize it as you need.

$("#label1").bind("keyup", changed).bind("change", changed);

function changed() {
    $("#label2").val(this.value
         .replace(/\s|,/g, '_')       /* replace with _ */
         .replace(/!/g, ''));         /* simply remove */
}

DEMO: http://jsfiddle.net/5sPZa/3/

According to your jsfiddle, you should write changed function in this way:

function changed() {
    var v = this.value.replace(/\W+/g, '-')
        .replace(/-+$/, '')
        .replace(/^-+/, '');

    $("#label2").val(v);
}
​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM