IT박스

두 날짜의 차이를 초 단위로 확인하려면 어떻게합니까?

itboxs 2020. 6. 12. 21:55
반응형

왜 x [0]! = x [0] [0]! = x [0] [0] [0]입니까?


나는 약간의 C ++을 공부하고 있으며 포인터와 싸우고 있습니다. 다음과 같이 선언하면 3 단계의 포인터를 가질 수 있음을 이해합니다.

int *(*x)[5];

그래서 이것은 *x포인터 인 5 개 요소의 배열에 대한 포인터 int입니다. 또한 내가 알고 x[0] = *(x+0);, x[1] = *(x+1)등등 및 ....

위의 선언에서 왜 그렇 x[0] != x[0][0] != x[0][0][0]습니까?


x에 대한 5 개의 포인터 배열에 대한 포인터 int입니다.
x[0]에 대한 5 개의 포인터 배열 입니다 int.
x[0][0]에 대한 포인터 int입니다.
x[0][0][0]입니다 int.

                       x[0]
   Pointer to array  +------+                                 x[0][0][0]         
x -----------------> |      |         Pointer to int           +-------+
               0x500 | 0x100| x[0][0]---------------->   0x100 |  10   |
x is a pointer to    |      |                                  +-------+
an array of 5        +------+                        
pointers to int      |      |         Pointer to int                             
               0x504 | 0x222| x[0][1]---------------->   0x222                    
                     |      |                                             
                     +------+                                             
                     |      |         Pointer to int                              
               0x508 | 0x001| x[0][2]---------------->   0x001                    
                     |      |                                             
                     +------+                                             
                     |      |         Pointer to int                              
               0x50C | 0x123| x[0][3]---------------->   0x123                    
                     |      |                                             
                     +------+                                             
                     |      |         Pointer to int                              
               0x510 | 0x000| x[0][4]---------------->   0x000                    
                     |      |                                             
                     +------+                                             

당신은 그것을 볼 수 있습니다

  • x[0]는 배열이며 표현식에서 사용될 때 첫 번째 요소에 대한 포인터로 변환됩니다 (일부 예외 제외). 따라서 x[0]첫 번째 요소의 주소 x[0][0]0x500입니다.
  • x[0][0]의 주소가 포함되어 int있는이 0x100.
  • x[0][0][0]int값을 포함합니다 10.

따라서 x[0]동일하다 &x[0][0]그러므로 및, &x[0][0] != x[0][0].
따라서 x[0] != x[0][0] != x[0][0][0].


x[0] != x[0][0] != x[0][0][0]

자신의 게시물에 따르면

*(x+0) != *(*(x+0)+0) != *(*(*(x+0)+0)+0)`  

이것은 단순화

*x != **x != ***x

왜 평등해야합니까?
첫 번째는 포인터의 주소입니다.
두 번째는 다른 포인터의 주소입니다.
그리고 세 번째는 int가치입니다.


다음은 포인터의 메모리 레이아웃입니다.

   +------------------+
x: | address of array |
   +------------------+
            |
            V
            +-----------+-----------+-----------+-----------+-----------+
            | pointer 0 | pointer 1 | pointer 2 | pointer 3 | pointer 4 |
            +-----------+-----------+-----------+-----------+-----------+
                  |
                  V
                  +--------------+
                  | some integer |
                  +--------------+

x[0]"어드레스 주소",
x[0][0]"포인터 0",
x[0][0][0]"일부 정수"를 나타냅니다.

나는 지금 분명해야한다고 생각한다. 왜 그들은 모두 다르다.


위의 내용은 기본적인 이해를 위해 충분히 가깝기 때문에 내가 쓴 방식으로 썼습니다. 그러나 헥스가 올바르게 지적했듯이 첫 번째 줄은 100 % 정확하지 않습니다. 자세한 내용은 다음과 같습니다.

C 언어의 정의에서 값 x[0]은 정수 포인터의 전체 배열입니다. 그러나 배열은 C에서 실제로 할 수없는 일입니다. 항상 주소 전체 또는 요소를 조작하고 전체 배열을 전체적으로 사용하지 마십시오.

  1. 운영자 x[0]에게 전달할 수 있습니다 sizeof. 그러나 그것은 실제로 값을 사용하는 것이 아니며 결과는 유형에만 달려 있습니다.

  2. 주소를 가져 와서 xtype의 "address of array" 값을 얻을 수 있습니다 int*(*)[5]. 다시 말해:&x[0] <=> &*(x + 0) <=> (x + 0) <=> x

  3. 에서는 모든 다른 콘텍스트 의 값은 x[0]상기 어레이의 첫번째 엘리먼트에 대한 포인터로 붕괴된다. 즉, "address of array"값과 유형이있는 포인터입니다 int**. 효과는 x유형의 포인터로 캐스팅 한 것과 같습니다 int**.

경우 3의 배열 포인터 붕괴로 인해, x[0]궁극적으로 모든 사용은 포인터 배열의 시작을 가리키는 포인터를 생성합니다. 이 호출 printf("%p", x[0])은 "어드레스 주소"라고 표시된 메모리 셀의 내용을 인쇄합니다.


  • x[0]가장 바깥 쪽 포인터 ( int에 대한 포인터의 크기 5의 배열을 가리키는 포인터)역 참조하고 포인터 의 크기가 5 인 배열을 만듭니다 int.
  • x[0][0]최 포인터 역 참조 포인터로 결과 인덱스 어레이 int;
  • x[0][0][0] 모든 것을 역 참조하여 구체적인 가치를 창출합니다.

그건 그렇고, 이러한 종류의 선언이 의미하는 것에 혼란 스러우면 cdecl을 사용하십시오 .


단계 식으로 단계를 고려하자 x[0], x[0][0]하고 x[0][0][0].

x다음과 같이 정의됩니다

int *(*x)[5];

expression x[0]은 유형의 배열입니다 int *[5]. expression x[0]expression 과 동일 하다는 점을 고려하십시오 *x. 즉, 배열에 대한 포인터를 참조하여 배열 자체를 얻습니다. 선언처럼 y와 같이 표시하자

int * y[5];

표현식은와 x[0][0]동일하며 y[0]유형이 int *있습니다. 우리가 선언을했다 z와 같이 표시하자

int *z;

expression x[0][0][0]y[0][0]expression z[0]동등하며 expression 동등하며 type을 갖습니다 int.

그래서 우리는

x[0] 유형이있다 int *[5]

x[0][0] 유형이있다 int *

x[0][0][0] 유형이있다 int

따라서 그것들은 다른 유형의 객체와 다른 크기의 객체입니다.

예를 들어 실행

std::cout << sizeof( x[0] ) << std::endl;
std::cout << sizeof( x[0][0] ) << std::endl;
std::cout << sizeof( x[0][0][0] ) << std::endl;

가장 먼저 말해야 할 것은

x [0] = * (x + 0) = * x;

x [0] [0] = * (* (x + 0) +0) = ** x;

x [0] [0] [0] = * (* (* (x + 0) +0)) = *** x;

따라서 * x ≠ * * x ≠ * * * x

다음 그림에서 모든 것이 명확합니다.

  x[0][0][0]= 2000

  x[0][0]   = 1001

  x[0]      = 10

enter image description here

x [0] [0] [0] = 10 인 경우의 예일뿐입니다.

그리고 어드레스 X [0] [0] [0] 이다 1,001

해당 주소는 x [0] [0] = 1001에 저장됩니다.

and address of x[0][0] is 2000

and that address is stored at x[0]=2000

So x[0][0][0] x[0][0] x[0]

.

EDITINGS

Program 1:

{
int ***x;
x=(int***)malloc(sizeof(int***));
*x=(int**)malloc(sizeof(int**));
**x=(int*)malloc(sizeof(int*));
***x=10;
printf("%d   %d   %d   %d\n",x,*x,**x,***x);
printf("%d   %d   %d   %d   %d",x[0][0][0],x[0][0],x[0],x,&x);
}

Output

142041096 142041112 142041128 10
10 142041128 142041112 142041096 -1076392836

Program 2:

{
int x[1][1][1]={10};
printf("%d   %d   %d   %d \n ",x[0][0][0],x[0][0],x[0],&x);
}

Output

10   -1074058436   -1074058436   -1074058436 

If you were to view the arrays from a real-world perspective, it would appear as thus:

x[0] is a freight container full of crates.
x[0][0] is a single crate, full of shoeboxes, within the freight container.
x[0][0][0] is a single shoebox inside the crate, inside the freight container.

Even if it were the only shoebox in the only crate in the freight container, it is still a shoebox and not a freight container


There's a principle in C++ so that: a declaration of a variable indicates exactly the way of using the variable. Consider your declaration:

int *(*x)[5];

that can be rewritten as (for clearer):

int *((*x)[5]);

Due to the principle, we have:

*((*x)[i]) is treated as an int value (i = 0..4)
→ (*x)[i] is treated as an int* pointer (i = 0..4)
→ *x is treated as an int** pointer
→ x is treated as an int*** pointer

Therefore:

x[0] is an int** pointer
→ x[0][0] = (x[0]) [0] is an int* pointer
→ x[0][0][0] = (x[0][0]) [0] is an int value

So you can figure out the difference.


Being p a pointer: you're stacking dereferences with p[0][0], which is equivalent to *((*(p+0))+0).

In C reference (&) and dereference (*) notation:

p == &p[0] == &(&p[0])[0] == &(&(&p[0])[0])[0])

Is equivalent to:

p == &*(p+0) == &*(&*(p+0))+0 == &*(&*(&*(p+0))+0)+0

Look that, the &* can be refactored, just removing it:

p == p+0 == p+0+0 == p+0+0+0 == (((((p+0)+0)+0)+0)+0)

You are trying to compare different types by value

If you take the addresses you might get more of what you expect

Keep in mind that your declaration makes a difference

 int y [5][5][5];

would allow the comparisons you want, since y, y[0], y[0][0], y[0][0][0] would have different values and types but the same address

int **x[5];

does not occupy contiguous space.

x and x [0] have the same address, but x[0][0] and x[0][0][0] are each at different addresses


The other answers are correct, but none of them emphasize the idea that it is possible for all three to contain the same value, and so they're in some way incomplete.

The reason this can't be understood from the other answers is that all the illustrations, while helpful and definitely reasonable under most circumstances, fail to cover the situation where the pointer x points to itself.

This is pretty easy to construct, but clearly a bit harder to understand. In the program below, we'll see how we can force all three values to be identical.

NOTE: The behavior in this program is undefined, but I'm posting it here purely as an interesting demonstration of something that pointers can do, but shouldn't.

#include <stdio.h>

int main () {
  int *(*x)[5];

  x = (int *(*)[5]) &x;

  printf("%p\n", x[0]);
  printf("%p\n", x[0][0]);
  printf("%p\n", x[0][0][0]);
}

This compiles without warnings in both C89 and C99, and the output is the following:

$ ./ptrs
0xbfd9198c
0xbfd9198c
0xbfd9198c

Interestingly enough, all three values are identical. But this shouldn't be a surprise! First, let's break down the program.

We declare x as a pointer to an array of 5 elements where each element is of type pointer to int. This declaration allocates 4 bytes on the runtime stack (or more depending on your implementation; on my machine pointers are 4 bytes), so x is referring to an actual memory location. In the C family of languages, the contents of x are just garbage, something left over from previous usage of the location, so x itself doesn't point anywhere—certainly not to allocated space.

So, naturally, we can take the address of the variable x and put it somewhere, so that's exactly what we do. But we'll go ahead and put it into x itself. Since &x has a different type than x, we need to do a cast so we don't get warnings.

The memory model would look something like this:

0xbfd9198c
+------------+
| 0xbfd9198c |
+------------+

So the 4-byte block of memory at the address 0xbfd9198c contains the bit pattern corresponding to the hexadecimal value 0xbfd9198c. Simple enough.

Next, we print out the three values. The other answers explain what each expression refers to, so the relationship should be clear now.

We can see that the values are the same, but only in a very low level sense...their bit patterns are identical, but the type data associated with each expression means their interpreted values are different. For instance, if we printed out x[0][0][0] using the format string %d, we'd get a huge negative number, so the "values" are, in practice, different, but the bit pattern is the same.

This is actually really simple...in the diagrams, the arrows just point to the same memory address rather than to different ones. However, while we were able to force an expected result out of undefined behavior, it is just that—undefined. This isn't production code but simply a demonstration for the sake of completeness.

In a reasonable situation, you will use malloc to create the array of 5 int pointers, and again to create the ints that are pointed to in that array. malloc always returns a unique address (unless you're out of memory, in which case it returns NULL or 0), so you'll never have to worry about self-referential pointers like this.

Hopefully that's the complete answer you're looking for. You shouldn't expect x[0], x[0][0], and x[0][0][0] to be equal, but they could be if forced. If anything went over your head, let me know so I can clarify!

참고URL : https://stackoverflow.com/questions/31231376/why-is-x0-x00-x000

pyspark에서 데이터 프레임 열 이름을 변경하는 방법은 무엇입니까?


팬더 배경에서 왔으며 CSV 파일의 데이터를 데이터 프레임으로 읽은 다음 간단한 명령을 사용하여 열 이름을 유용한 것으로 변경하는 데 익숙합니다.

df.columns = new_column_name_list

그러나 sqlContext를 사용하여 생성 된 pyspark 데이터 프레임에서도 마찬가지입니다. 이 작업을 쉽게 수행 할 수있는 유일한 해결책은 다음과 같습니다.

df = sqlContext.read.format("com.databricks.spark.csv").options(header='false', inferschema='true', delimiter='\t').load("data.txt")
oldSchema = df.schema
for i,k in enumerate(oldSchema.fields):
  k.name = new_column_name_list[i]
df = sqlContext.read.format("com.databricks.spark.csv").options(header='false', delimiter='\t').load("data.txt", schema=oldSchema)

기본적으로 변수를 두 번 정의하고 스키마를 먼저 유추 한 다음 열 이름을 바꾸고 업데이트 된 스키마로 데이터 프레임을 다시로드합니다.

우리가 판다에서하는 것처럼 더 좋고 효율적인 방법이 있습니까?

내 스파크 버전은 1.5.0입니다


여러 가지 방법이 있습니다.

  • 옵션 1. 사용 selectExpr을 .

    data = sqlContext.createDataFrame([("Alberto", 2), ("Dakota", 2)], 
                                      ["Name", "askdaosdka"])
    data.show()
    data.printSchema()
    
    # Output
    #+-------+----------+
    #|   Name|askdaosdka|
    #+-------+----------+
    #|Alberto|         2|
    #| Dakota|         2|
    #+-------+----------+
    
    #root
    # |-- Name: string (nullable = true)
    # |-- askdaosdka: long (nullable = true)
    
    df = data.selectExpr("Name as name", "askdaosdka as age")
    df.show()
    df.printSchema()
    
    # Output
    #+-------+---+
    #|   name|age|
    #+-------+---+
    #|Alberto|  2|
    #| Dakota|  2|
    #+-------+---+
    
    #root
    # |-- name: string (nullable = true)
    # |-- age: long (nullable = true)
    
  • 옵션 2. withColumnRenamed를 사용하면 이 방법으로 같은 열을 "덮어 쓸 수 있습니다".

    oldColumns = data.schema.names
    newColumns = ["name", "age"]
    
    df = reduce(lambda data, idx: data.withColumnRenamed(oldColumns[idx], newColumns[idx]), xrange(len(oldColumns)), data)
    df.printSchema()
    df.show()
    
  • 사용 옵션 3. 별명은 스칼라에서 당신은 또한 사용할 수 있습니다 .

    from pyspark.sql.functions import col
    
    data = data.select(col("Name").alias("name"), col("askdaosdka").alias("age"))
    data.show()
    
    # Output
    #+-------+---+
    #|   name|age|
    #+-------+---+
    #|Alberto|  2|
    #| Dakota|  2|
    #+-------+---+
    
  • 옵션 4. sqlContext.sql 사용 DataFrames: 테이블로 등록 된 SQL 쿼리를 사용할 수 있습니다 .

    sqlContext.registerDataFrameAsTable(data, "myTable")
    df2 = sqlContext.sql("SELECT Name AS name, askdaosdka as age from myTable")
    
    df2.show()
    
    # Output
    #+-------+---+
    #|   name|age|
    #+-------+---+
    #|Alberto|  2|
    #| Dakota|  2|
    #+-------+---+
    

df = df.withColumnRenamed("colName", "newColName")
       .withColumnRenamed("colName2", "newColName2")

이 방법을 사용할 때의 장점 : 열 목록이 길면 몇 개의 열 이름 만 변경하려고합니다. 이 시나리오에서는 매우 편리 할 수 ​​있습니다. 중복 열 이름을 가진 테이블을 조인 할 때 매우 유용합니다.


모든 열 이름을 변경하려면 시도하십시오 df.toDF(*cols)


모든 열 이름에 간단한 변환을 적용하려는 경우이 코드는 트릭을 수행합니다. (모든 공백을 밑줄로 바꿉니다)

new_column_name_list= list(map(lambda x: x.replace(" ", "_"), df.columns))

df = df.toDF(*new_column_name_list)

toDf트릭을 위한 @ user8117731에게 감사합니다 .


df.withColumnRenamed('age', 'age2')


If you want to rename a single column and keep the rest as it is:

from pyspark.sql.functions import col
new_df = old_df.select(*[col(s).alias(new_name) if s == column_to_change else s for s in old_df.columns])

this is the approach that I used:

create pyspark session:

import pyspark
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('changeColNames').getOrCreate()

create dataframe:

df = spark.createDataFrame(data = [('Bob', 5.62,'juice'),  ('Sue',0.85,'milk')], schema = ["Name", "Amount","Item"])

view df with column names:

df.show()
+----+------+-----+
|Name|Amount| Item|
+----+------+-----+
| Bob|  5.62|juice|
| Sue|  0.85| milk|
+----+------+-----+

create a list with new column names:

newcolnames = ['NameNew','AmountNew','ItemNew']

change the column names of the df:

for c,n in zip(df.columns,newcolnames):
    df=df.withColumnRenamed(c,n)

view df with new column names:

df.show()
+-------+---------+-------+
|NameNew|AmountNew|ItemNew|
+-------+---------+-------+
|    Bob|     5.62|  juice|
|    Sue|     0.85|   milk|
+-------+---------+-------+

I made an easy to use function to rename multiple columns for a pyspark dataframe, in case anyone wants to use it:

def renameCols(df, old_columns, new_columns):
    for old_col,new_col in zip(old_columns,new_columns):
        df = df.withColumnRenamed(old_col,new_col)
    return df

old_columns = ['old_name1','old_name2']
new_columns = ['new_name1', 'new_name2']
df_renamed = renameCols(df, old_columns, new_columns)

Be careful, both lists must be the same lenght.


Another way to rename just one column (using import pyspark.sql.functions as F):

df = df.select( '*', F.col('count').alias('new_count') ).drop('count')

I use this one:

from pyspark.sql.functions import col
df.select(['vin',col('timeStamp').alias('Date')]).show()

For a single column rename, you can still use toDF(). For example,

df1.selectExpr("SALARY*2").toDF("REVISED_SALARY").show()

참고URL : https://stackoverflow.com/questions/34077353/how-to-change-dataframe-column-names-in-pyspark

jQuery에서 제목을 URL 슬러그로 변환하는 방법은 무엇입니까?


CodeIgniter에서 앱을 작성 중이며 양식의 필드를 동적으로 생성하여 URL 슬러그를 생성하려고합니다. 내가하고 싶은 것은 문장 부호를 제거하고 소문자로 변환 한 다음 공백을 하이픈으로 바꾸는 것입니다. 예를 들어 Shane의 Rib Shack은 shanes-rib-shack이됩니다.

여기까지 내가 가진 것입니다. 소문자는 쉽지만 대체 기능이 전혀 작동하지 않는 것 같습니다. 구두점을 제거 할 생각이 없습니다.

$("#Restaurant_Name").keyup(function(){
    var Text = $(this).val();
    Text = Text.toLowerCase();
    Text = Text.replace('/\s/g','-');
    $("#Restaurant_Slug").val(Text);    
});

나는 '슬러그'용어가 어디에서 왔는지 전혀 알지 못하지만 여기서 간다.

function convertToSlug(Text)
{
    return Text
        .toLowerCase()
        .replace(/ /g,'-')
        .replace(/[^\w-]+/g,'')
        ;
}

첫 번째 바꾸기는 공백을 하이픈으로 바꾸고 두 번째 바꾸기는 영숫자, 밑줄 또는 하이픈이 아닌 것을 제거합니다.

"like-this"를 "like --- this"로 바꾸지 않으려면 대신 다음을 사용하십시오.

function convertToSlug(Text)
{
    return Text
        .toLowerCase()
        .replace(/[^\w ]+/g,'')
        .replace(/ +/g,'-')
        ;
}

첫 번째 대치에서 하이픈 (공백은 아님)을 제거하고 두 번째 대치에서는 연속 된 공백을 단일 하이픈으로 압축합니다.

따라서 "like-this"는 "like-this"로 나타납니다.


var slug = function(str) {
  str = str.replace(/^\s+|\s+$/g, ''); // trim
  str = str.toLowerCase();

  // remove accents, swap ñ for n, etc
  var from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;";
  var to   = "aaaaaeeeeeiiiiooooouuuunc------";
  for (var i=0, l=from.length ; i<l ; i++) {
    str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
  }

  str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
    .replace(/\s+/g, '-') // collapse whitespace and replace by -
    .replace(/-+/g, '-'); // collapse dashes

  return str;
};

시도

slug($('#field').val())

원본 : http://dense13.com/blog/2009/05/03/converting-string-to-slug-javascript/


편집 : 더 많은 언어 별 문자로 확장 :

var from = "ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆĞÍÌÎÏİŇÑÓÖÒÔÕØŘŔŠŞŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇğíìîïıňñóöòôõøðřŕšşťúůüùûýÿžþÞĐđßÆa·/_,:;";
var to   = "AAAAAACCCDEEEEEEEEGIIIIINNOOOOOORRSSTUUUUUYYZaaaaaacccdeeeeeeeegiiiiinnooooooorrsstuuuuuyyzbBDdBAa------";

우선, 정규 표현식에는 따옴표가 없어야하므로 '/ \ s / g'/ \ s / g 여야합니다.

영숫자가 아닌 모든 문자를 대시로 바꾸려면 예제 코드를 사용하여 작동합니다.

$("#Restaurant_Name").keyup(function(){
        var Text = $(this).val();
        Text = Text.toLowerCase();
        Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
        $("#Restaurant_Slug").val(Text);        
});

그 트릭을해야합니다 ...


당신이 필요로하는 것은 플러스 :)

$("#Restaurant_Name").keyup(function(){
        var Text = $(this).val();
        Text = Text.toLowerCase();
        var regExp = /\s+/g;
        Text = Text.replace(regExp,'-');
        $("#Restaurant_Slug").val(Text);        
});

이것이 누군가의 하루를 구할 수 있기를 바랍니다 ...

/* Encode string to slug */
function convertToSlug( str ) {
	
  //replace all special characters | symbols with a space
  str = str.replace(/[`~!@#$%^&*()_\-+=\[\]{};:'"\\|\/,.<>?\s]/g, ' ').toLowerCase();
	
  // trim spaces at start and end of string
  str = str.replace(/^\s+|\s+$/gm,'');
	
  // replace space with dash/hyphen
  str = str.replace(/\s+/g, '-');	
  document.getElementById("slug-text").innerHTML= str;
  //return str;
}
<input type="text" onload="convertToSlug(this.value)" onkeyup="convertToSlug(this.value)" value="Try it Yourself"/>
<p id="slug-text"></p>


https://gist.github.com/sgmurphy/3095196 에서 Sean Murphy가 개발 한 URL을 삭제하기 위해이 슬러그 기능을 살펴보십시오.

/**
 * Create a web friendly URL slug from a string.
 *
 * Requires XRegExp (http://xregexp.com) with unicode add-ons for UTF-8 support.
 *
 * Although supported, transliteration is discouraged because
 *     1) most web browsers support UTF-8 characters in URLs
 *     2) transliteration causes a loss of information
 *
 * @author Sean Murphy <sean@iamseanmurphy.com>
 * @copyright Copyright 2012 Sean Murphy. All rights reserved.
 * @license http://creativecommons.org/publicdomain/zero/1.0/
 *
 * @param string s
 * @param object opt
 * @return string
 */
function url_slug(s, opt) {
    s = String(s);
    opt = Object(opt);

    var defaults = {
        'delimiter': '-',
        'limit': undefined,
        'lowercase': true,
        'replacements': {},
        'transliterate': (typeof(XRegExp) === 'undefined') ? true : false
    };

    // Merge options
    for (var k in defaults) {
        if (!opt.hasOwnProperty(k)) {
            opt[k] = defaults[k];
        }
    }

    var char_map = {
        // Latin
        'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A', 'Å': 'A', 'Æ': 'AE', 'Ç': 'C', 
        'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E', 'Ì': 'I', 'Í': 'I', 'Î': 'I', 'Ï': 'I', 
        'Ð': 'D', 'Ñ': 'N', 'Ò': 'O', 'Ó': 'O', 'Ô': 'O', 'Õ': 'O', 'Ö': 'O', 'Ő': 'O', 
        'Ø': 'O', 'Ù': 'U', 'Ú': 'U', 'Û': 'U', 'Ü': 'U', 'Ű': 'U', 'Ý': 'Y', 'Þ': 'TH', 
        'ß': 'ss', 
        'à': 'a', 'á': 'a', 'â': 'a', 'ã': 'a', 'ä': 'a', 'å': 'a', 'æ': 'ae', 'ç': 'c', 
        'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e', 'ì': 'i', 'í': 'i', 'î': 'i', 'ï': 'i', 
        'ð': 'd', 'ñ': 'n', 'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 'o', 'ö': 'o', 'ő': 'o', 
        'ø': 'o', 'ù': 'u', 'ú': 'u', 'û': 'u', 'ü': 'u', 'ű': 'u', 'ý': 'y', 'þ': 'th', 
        'ÿ': 'y',

        // Latin symbols
        '©': '(c)',

        // Greek
        'Α': 'A', 'Β': 'B', 'Γ': 'G', 'Δ': 'D', 'Ε': 'E', 'Ζ': 'Z', 'Η': 'H', 'Θ': '8',
        'Ι': 'I', 'Κ': 'K', 'Λ': 'L', 'Μ': 'M', 'Ν': 'N', 'Ξ': '3', 'Ο': 'O', 'Π': 'P',
        'Ρ': 'R', 'Σ': 'S', 'Τ': 'T', 'Υ': 'Y', 'Φ': 'F', 'Χ': 'X', 'Ψ': 'PS', 'Ω': 'W',
        'Ά': 'A', 'Έ': 'E', 'Ί': 'I', 'Ό': 'O', 'Ύ': 'Y', 'Ή': 'H', 'Ώ': 'W', 'Ϊ': 'I',
        'Ϋ': 'Y',
        'α': 'a', 'β': 'b', 'γ': 'g', 'δ': 'd', 'ε': 'e', 'ζ': 'z', 'η': 'h', 'θ': '8',
        'ι': 'i', 'κ': 'k', 'λ': 'l', 'μ': 'm', 'ν': 'n', 'ξ': '3', 'ο': 'o', 'π': 'p',
        'ρ': 'r', 'σ': 's', 'τ': 't', 'υ': 'y', 'φ': 'f', 'χ': 'x', 'ψ': 'ps', 'ω': 'w',
        'ά': 'a', 'έ': 'e', 'ί': 'i', 'ό': 'o', 'ύ': 'y', 'ή': 'h', 'ώ': 'w', 'ς': 's',
        'ϊ': 'i', 'ΰ': 'y', 'ϋ': 'y', 'ΐ': 'i',

        // Turkish
        'Ş': 'S', 'İ': 'I', 'Ç': 'C', 'Ü': 'U', 'Ö': 'O', 'Ğ': 'G',
        'ş': 's', 'ı': 'i', 'ç': 'c', 'ü': 'u', 'ö': 'o', 'ğ': 'g', 

        // Russian
        'А': 'A', 'Б': 'B', 'В': 'V', 'Г': 'G', 'Д': 'D', 'Е': 'E', 'Ё': 'Yo', 'Ж': 'Zh',
        'З': 'Z', 'И': 'I', 'Й': 'J', 'К': 'K', 'Л': 'L', 'М': 'M', 'Н': 'N', 'О': 'O',
        'П': 'P', 'Р': 'R', 'С': 'S', 'Т': 'T', 'У': 'U', 'Ф': 'F', 'Х': 'H', 'Ц': 'C',
        'Ч': 'Ch', 'Ш': 'Sh', 'Щ': 'Sh', 'Ъ': '', 'Ы': 'Y', 'Ь': '', 'Э': 'E', 'Ю': 'Yu',
        'Я': 'Ya',
        'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'е': 'e', 'ё': 'yo', 'ж': 'zh',
        'з': 'z', 'и': 'i', 'й': 'j', 'к': 'k', 'л': 'l', 'м': 'm', 'н': 'n', 'о': 'o',
        'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u', 'ф': 'f', 'х': 'h', 'ц': 'c',
        'ч': 'ch', 'ш': 'sh', 'щ': 'sh', 'ъ': '', 'ы': 'y', 'ь': '', 'э': 'e', 'ю': 'yu',
        'я': 'ya',

        // Ukrainian
        'Є': 'Ye', 'І': 'I', 'Ї': 'Yi', 'Ґ': 'G',
        'є': 'ye', 'і': 'i', 'ї': 'yi', 'ґ': 'g',

        // Czech
        'Č': 'C', 'Ď': 'D', 'Ě': 'E', 'Ň': 'N', 'Ř': 'R', 'Š': 'S', 'Ť': 'T', 'Ů': 'U', 
        'Ž': 'Z', 
        'č': 'c', 'ď': 'd', 'ě': 'e', 'ň': 'n', 'ř': 'r', 'š': 's', 'ť': 't', 'ů': 'u',
        'ž': 'z', 

        // Polish
        'Ą': 'A', 'Ć': 'C', 'Ę': 'e', 'Ł': 'L', 'Ń': 'N', 'Ó': 'o', 'Ś': 'S', 'Ź': 'Z', 
        'Ż': 'Z', 
        'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ó': 'o', 'ś': 's', 'ź': 'z',
        'ż': 'z',

        // Latvian
        'Ā': 'A', 'Č': 'C', 'Ē': 'E', 'Ģ': 'G', 'Ī': 'i', 'Ķ': 'k', 'Ļ': 'L', 'Ņ': 'N', 
        'Š': 'S', 'Ū': 'u', 'Ž': 'Z', 
        'ā': 'a', 'č': 'c', 'ē': 'e', 'ģ': 'g', 'ī': 'i', 'ķ': 'k', 'ļ': 'l', 'ņ': 'n',
        'š': 's', 'ū': 'u', 'ž': 'z'
    };

    // Make custom replacements
    for (var k in opt.replacements) {
        s = s.replace(RegExp(k, 'g'), opt.replacements[k]);
    }

    // Transliterate characters to ASCII
    if (opt.transliterate) {
        for (var k in char_map) {
            s = s.replace(RegExp(k, 'g'), char_map[k]);
        }
    }

    // Replace non-alphanumeric characters with our delimiter
    var alnum = (typeof(XRegExp) === 'undefined') ? RegExp('[^a-z0-9]+', 'ig') : XRegExp('[^\\p{L}\\p{N}]+', 'ig');
    s = s.replace(alnum, opt.delimiter);

    // Remove duplicate delimiters
    s = s.replace(RegExp('[' + opt.delimiter + ']{2,}', 'g'), opt.delimiter);

    // Truncate slug to max. characters
    s = s.substring(0, opt.limit);

    // Remove delimiter from ends
    s = s.replace(RegExp('(^' + opt.delimiter + '|' + opt.delimiter + '$)', 'g'), '');

    return opt.lowercase ? s.toLowerCase() : s;
}

나는 영어를위한 좋고 완전한 해결책을 찾았다

function slugify(string) {
  return string
    .toString()
    .trim()
    .toLowerCase()
    .replace(/\s+/g, "-")
    .replace(/[^\w\-]+/g, "")
    .replace(/\-\-+/g, "-")
    .replace(/^-+/, "")
    .replace(/-+$/, "");
}

사용중인 일부 예 :

slugify(12345);
// "12345"

slugify("  string with leading   and   trailing whitespace    ");
// "string-with-leading-and-trailing-whitespace"

slugify("mIxEd CaSe TiTlE");
// "mixed-case-title"

slugify("string with - existing hyphens -- ");
// "string-with-existing-hyphens"

slugify("string with Special™ characters");
// "string-with-special-characters"

Andrew Stewart 에게 감사합니다


대부분의 언어로 구현할 플러그인을 만듭니다. http://leocaseiro.com.br/jquery-plugin-string-to-slug/

기본 사용법 :

$(document).ready( function() {
    $("#string").stringToSlug();
});

stringToSlug jQuery 플러그인이 매우 쉽습니다.


function slugify(text){
  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/[^\u0100-\uFFFF\w\-]/g,'-') // Remove all non-word chars ( fix for UTF-8 chars )
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '');            // Trim - from end of text
}

* https://gist.github.com/mathewbyrne/1280286 기반

이제이 문자열을 변환 할 수 있습니다 :

Barack_Obama       Барак_Обама ~!@#$%^&*()+/-+?><:";'{}[]\|`

으로:

barack_obama-барак_обама

코드에 적용 :

$("#Restaurant_Name").keyup(function(){
    var Text = $(this).val();
    Text = slugify(Text);
    $("#Restaurant_Slug").val(Text);
});

이를 위해 자신의 기능을 사용할 수 있습니다.

시도해보십시오 : http://jsfiddle.net/xstLr7aj/

function string_to_slug(str) {
  str = str.replace(/^\s+|\s+$/g, ''); // trim
  str = str.toLowerCase();

  // remove accents, swap ñ for n, etc
  var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
  var to   = "aaaaeeeeiiiioooouuuunc------";
  for (var i=0, l=from.length ; i<l ; i++) {
    str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
  }

  str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
    .replace(/\s+/g, '-') // collapse whitespace and replace by -
    .replace(/-+/g, '-'); // collapse dashes

  return str;
}
$(document).ready(function() {
    $('#test').submit(function(){
        var val = string_to_slug($('#t').val());
        alert(val);
        return false;
    });
});

허용 된 답변이 내 요구를 충족시키지 못했습니다 (밑줄을 허용하고 시작과 끝에서 대시를 처리하지 않는 등). 다른 답변에는 사용 사례에 맞지 않는 다른 문제가 있었으므로 여기에 slugify 함수가 있습니다. 나는 생각해 냈다 :

function slugify(string) {
    return string.trim() // Remove surrounding whitespace.
    .toLowerCase() // Lowercase.
    .replace(/[^a-z0-9]+/g,'-') // Find everything that is not a lowercase letter or number, one or more times, globally, and replace it with a dash.
    .replace(/^-+/, '') // Remove all dashes from the beginning of the string.
    .replace(/-+$/, ''); // Remove all dashes from the end of the string.
}

이것은 'foo !!! BAR _-_-_ baz-'(처음에는 공백에주의)로 바뀝니다 foo-bar-baz.


speakingURL 플러그인을 살펴보고 싶을 수도 있습니다.

    $("#Restaurant_Name").on("keyup", function () {
        var slug = getSlug($("#Restaurant_Name").val());
        $("#Restaurant_Slug").val(slug);
    });

또 하나. 특수 문자를 짧게 유지합니다.

imaginação é mato => imaginacao-e-mato

function slugify (text) {
  const a = 'àáäâãèéëêìíïîòóöôùúüûñçßÿœæŕśńṕẃǵǹḿǘẍźḧ·/_,:;'
  const b = 'aaaaaeeeeiiiioooouuuuncsyoarsnpwgnmuxzh------'
  const p = new RegExp(a.split('').join('|'), 'g')

  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(p, c =>
        b.charAt(a.indexOf(c)))     // Replace special chars
    .replace(/&/g, '-and-')         // Replace & with 'and'
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '')             // Trim - from end of text
}

순수한 JavaScript에서보다 강력한 슬러그 생성 방법. 기본적으로 모든 키릴 문자 및 많은 움라우트 (독일어, 덴마크어, 프랑스, ​​터키어, 우크라이나어 등)의 음역을 지원하지만 쉽게 확장 할 수 있습니다.

function makeSlug(str)
{
  var from="а б в г д е ё ж з и й к л м н о п р с т у ф х ц ч ш щ ъ ы ь э ю я ā ą ä á à â å č ć ē ę ě é è ê æ ģ ğ ö ó ø ǿ ô ő ḿ ʼn ń ṕ ŕ ş ü ß ř ł đ þ ĥ ḧ ī ï í î ĵ ķ ł ņ ń ň ř š ś ť ů ú û ứ ù ü ű ū ý ÿ ž ź ż ç є ґ".split(' ');
  var to=  "a b v g d e e zh z i y k l m n o p r s t u f h ts ch sh shch # y # e yu ya a a ae a a a a c c e e e e e e e g g oe o o o o o m n n p r s ue ss r l d th h h i i i i j k l n n n r s s t u u u u u u u u y y z z z c ye g".split(' ');
	
  str = str.toLowerCase();
  
  // remove simple HTML tags
  str = str.replace(/(<[a-z0-9\-]{1,15}[\s]*>)/gi, '');
  str = str.replace(/(<\/[a-z0-9\-]{1,15}[\s]*>)/gi, '');
  str = str.replace(/(<[a-z0-9\-]{1,15}[\s]*\/>)/gi, '');
  
  str = str.replace(/^\s+|\s+$/gm,''); // trim spaces
  
  for(i=0; i<from.length; ++i)
    str = str.split(from[i]).join(to[i]);
  
  // Replace different kind of spaces with dashes
  var spaces = [/(&nbsp;|&#160;|&#32;)/gi, /(&mdash;|&ndash;|&#8209;)/gi,
     /[(_|=|\\|\,|\.|!)]+/gi, /\s/gi];

  for(i=0; i<from.length; ++i)
  	str = str.replace(spaces[i], '-');
  str = str.replace(/-{2,}/g, "-");

  // remove special chars like &amp;
  str = str.replace(/&[a-z]{2,7};/gi, '');
  str = str.replace(/&#[0-9]{1,6};/gi, '');
  str = str.replace(/&#x[0-9a-f]{1,6};/gi, '');
  
  str = str.replace(/[^a-z0-9\-]+/gmi, ""); // remove all other stuff
  str = str.replace(/^\-+|\-+$/gm,''); // trim edges
  
  return str;
};


document.getElementsByTagName('pre')[0].innerHTML = makeSlug(" <br/> &#x202A;Про&amp;вер<strong>ка_тран</strong>с…литеърьации\rюга\nи&ndash;южного&nbsp;округа\t \nс\tёжикам&#180;и&nbsp;со\\всеми&ndash;друзьями\tтоже.Danke schön!ich heiße=КáÞÿá-Skånske,København çağatay rí gé tőr zöldülésetekről - . ");
<div>
  <pre>Hello world!</pre>
</div>


이미 사용중인 사람들을 위해 lodash

이 예제의 대부분은 실제로 훌륭하며 많은 경우를 다룹니다. 그러나 영어 텍스트 만 가지고 있음을 '알고 있다면'읽기 쉬운 내 버전이 있습니다. :)

_.words(_.toLower(text)).join('-')


여기 답변의 다양한 요소를 정규화와 결합하면 좋은 적용 범위를 제공합니다. URL을 점진적으로 정리하려면 작업 순서를 유지하십시오.

function clean_url(s) {
    return s.toString().normalize('NFD').replace(/[\u0300-\u036f]/g, "") //remove diacritics
            .toLowerCase()
            .replace(/\s+/g, '-') //spaces to dashes
            .replace(/&/g, '-and-') //ampersand to and
            .replace(/[^\w\-]+/g, '') //remove non-words
            .replace(/\-\-+/g, '-') //collapse multiple dashes
            .replace(/^-+/, '') //trim starting dash
            .replace(/-+$/, ''); //trim ending dash
}

normlize('NFD')악센트 문자를 기본 문자와 분음 부호 (악센트 부분)로 구성 요소로 나눕니다. replace(/[\u0300-\u036f]/g, "")기본 발음은 그대로두고 모든 분음 부호를 제거합니다. 나머지는 인라인 주석으로 설명됩니다.


글쎄, 대답을 읽은 후에 나는 이것을 찾았습니다.

    const generateSlug = (text) => text.toLowerCase().trim().replace(/[^\w- ]+/g, '').replace(/ /g, '-').replace(/[-]+/g, '-');

//
//  jQuery Slug Plugin by Perry Trinier (perrytrinier@gmail.com)
//  MIT License: http://www.opensource.org/licenses/mit-license.php

jQuery.fn.slug = function(options) {
var settings = {
    slug: 'slug', // Class used for slug destination input and span. The span is created on $(document).ready() 
    hide: true   // Boolean - By default the slug input field is hidden, set to false to show the input field and hide the span. 
};

if(options) {
    jQuery.extend(settings, options);
}

$this = $(this);

$(document).ready( function() {
    if (settings.hide) {
        $('input.' + settings.slug).after("<span class="+settings.slug+"></span>");
        $('input.' + settings.slug).hide();
    }
});

makeSlug = function() {
        var slug = jQuery.trim($this.val()) // Trimming recommended by Brooke Dukes - http://www.thewebsitetailor.com/2008/04/jquery-slug-plugin/comment-page-1/#comment-23
                    .replace(/\s+/g,'-').replace(/[^a-zA-Z0-9\-]/g,'').toLowerCase() // See http://www.djangosnippets.org/snippets/1488/ 
                    .replace(/\-{2,}/g,'-'); // If we end up with any 'multiple hyphens', replace with just one. Temporary bugfix for input 'this & that'=>'this--that'
        $('input.' + settings.slug).val(slug);
        $('span.' + settings.slug).text(slug);

    }

$(this).keyup(makeSlug);

return $this;
    };

이것은 같은 문제를 해결하는 데 도움이되었습니다!


참고 : 수락 된 답변에 대한 논쟁에 신경 쓰지 않고 답변을 찾고 있다면 다음 섹션을 건너 뛰십시오. 마지막에 제안 된 답변을 찾을 수 있습니다

수락 된 답변에는 몇 가지 문제가 있습니다 (제 의견으로는).

1) 첫 번째 함수 스 니펫 :

여러 개의 연속 공백을 고려하지 않음

입력: is it a good slug

받았습니다 : ---is---it---a---good---slug---

예상 : is-it-a-good-slug

여러 개의 연속 대시를 고려하지 않음

입력: -----is-----it-----a-----good-----slug-----

받았습니다 : -----is-----it-----a-----good-----slug-----

예상 : is-it-a-good-slug

이 구현은 외부 대시 (또는 그 문제에 대한 공백)를 여러 연속 연속 문자 또는 단일 문자 (슬러그 및 그 사용법을 이해하는 한)가 아닌 경우 처리하지 않습니다.

2) 두 번째 함수 스 니펫 :

그것은 하나의로 변환하여 연속 된 여러 공백을 담당 -하지만, 그래서 공백이 동일하게 처리됩니다 (시작과 문자열의 끝에서) 외부로는 충분하지 않습니다 is it a good slug반환-is-it-a-good-slug-

또한 같은 것을 변환 입력에서 모두 대시 제거 --is--it--a--good--slug--'isitagoodslug라이언 앨런은 외부 대시가 해결되지 않은 생각을 발행 떠나, 그 처리합니다 @으로 주석에, 스 니펫을

이제 슬러그에 대한 표준 정의가 없으며 승인 된 답변이 작업 (질문을 게시 한 사용자가 찾고 있던)을 수행 할 수 있지만 JS의 슬러그에 대한 가장 인기있는 SO 질문이므로 해당 문제 ( 작업을 완료하는 것과 관련하여) 지적해야했습니다 ( URL www.blog.com/posts/-----how-----to-----slugify-----a-----string-----) 의이 혐오를 입력 하거나 ( www.blog.com/posts/how-to-slugify-a-string) 와 같이 대신 리디렉션되도록 상상해보십시오. 이것은 극단적 인 경우이지만 알고있는 것은 테스트입니다. 입니다.

내 의견으로 는 더 나은 해결책 은 다음과 같습니다.

const slugify = str =>
  str
  .trim()                      // remove whitespaces at the start and end of string
  .toLowerCase()              
  .replace(/^-+/g, "")         // remove one or more dash at the start of the string
  .replace(/[^\w-]+/g, "-")    // convert any on-alphanumeric character to a dash
  .replace(/-+/g, "-")         // convert consecutive dashes to singuar one
  .replace(/-+$/g, "");        // remove one or more dash at the end of the string

이제 RegExp 닌자가있을 수 있습니다.이를 하나의 라이너 식으로 변환 할 수 있습니다 .RegExp의 전문가가 아니며 이것이 최고의 또는 가장 컴팩트 한 솔루션이거나 최고의 성능을 가진 솔루션이라고 말하는 것이 아닙니다 그러나 잘하면 그것은 일을 끝낼 수 있습니다.


private string ToSeoFriendly(string title, int maxLength) {
    var match = Regex.Match(title.ToLower(), "[\\w]+");
    StringBuilder result = new StringBuilder("");
    bool maxLengthHit = false;
    while (match.Success && !maxLengthHit) {
        if (result.Length + match.Value.Length <= maxLength) {
            result.Append(match.Value + "-");
        } else {
            maxLengthHit = true;
            // Handle a situation where there is only one word and it is greater than the max length.
            if (result.Length == 0) result.Append(match.Value.Substring(0, maxLength));
        }
        match = match.NextMatch();
    }
    // Remove trailing '-'
    if (result[result.Length - 1] == '-') result.Remove(result.Length - 1, 1);
    return result.ToString();
}

참고 URL : https://stackoverflow.com/questions/1053902/how-to-convert-a-title-to-a-url-slug-in-jquery

반응형