1

私がやろうとしているのは: 文字列を取る

  1. 英数字以外はすべて削除してください。
  2. また、空白を - に変えようとしています (複数の空白は単一の - になります)。
  3. すべて小文字に変換

これは、ユーザー入力からわかりやすい URL を生成するためです。

これは私がこれまで持っているすべてです

var str = "This is    a really bad Url _, *7% !";
result1 = str.replace(/\s+/g, '-').toLowerCase();
alert(result1); 
4

5 に答える 5

3

これはトリックを行うことができます

var str = "This is    a really bad Url _, *7% !";
result1 = str.replace(/[^a-zA-Z0-9\s]/g, '') // Remove non alphanum except whitespace
             .replace(/^\s+|\s+$/, '')      // Remove leading and trailing whitespace
             .replace(/\s+/g, '-')          // Replace (multiple) whitespaces with a dash
             .toLowerCase();
alert(result1); 

結果 :

this-is-a-really-bad-url-7
于 2013-07-08T14:08:02.513 に答える
0
var str = "This is    a really bad Url _, *7% !";
result1 = str
            .replace(/[^A-Za-z\d\s]+/g, "")  //delete all non alphanumeric characters, don't touch the spaces
            .replace(/\s+/g, '-')             //change the spaces for -
            .toLowerCase();                   //lowercase

alert(result1); 
于 2013-07-08T14:05:17.773 に答える
0

私はこれらすべてを見ましたが、いくつかのことを見逃していました。

var stripped = string.toLowerCase() // first lowercase for it to be easier
            .replace(/^\s+|\s+$/, '') // THEN leading and trailing whitespace. We do not want "hello-world-"
            .replace(/\s+/g, '-') // THEN replace spaces with -
            .replace(/[^a-z0-9-\s]/g, '');// Lastly
于 2016-05-13T20:56:11.953 に答える
0

あなたはこれを行うことができます

var output=input.replace(/[^A-Za-z\d\s]+/g,"").replace(/\s+/g," ").toLowerCase();
于 2013-07-08T14:04:09.157 に答える
0

すでに得ているものを拡張します。最初に空白をハイフンに変換し、次に文字、数字、ハイフン以外のすべてを空の文字列に置き換え、最後に小文字に変換します。

var str = "This is    a really bad Url _, *7% !";
result1 = str.replace(/\s+/g, '-').replace(/[^a-zA-Z\d-]/g, '').toLowerCase();
alert(result1);

また、文字列の最初のハイフン ('-') をどうするかを考える必要があります。上記の私のコードはそれらを保持します。それらも削除する場合は、2行目を次のように変更します

result1 = str.replace(/[^A-Za-z\d\s]/g, '').replace(/\s+/g, '-').toLowerCase();
于 2013-07-08T14:04:37.813 に答える