我有這個字符串"Gem. Buitentemperatuur (etmaal)"
的Javascript使用正則表達式來代替空格和其他charaters
,我想,這樣我與
"gem_buitentemperatuur_etmaal"
我有這個字符串"Gem. Buitentemperatuur (etmaal)"
的Javascript使用正則表達式來代替空格和其他charaters
,我想,這樣我與
"gem_buitentemperatuur_etmaal"
試試這個
var yourStr = "Gem. Buitentemperatuur (etmaal)";
var newStr = yourStr.replace(/\s+/g, "_").replace(/\W+/g, "").toLowerCase();
//gem_buitentemperatuur_etmaal
.replace()被用來操縱你的字符串,一個簡單的正則表達式被傳遞到這一點,你想
首先來取代它的價值,我們更換空白。
/ <- start the regex
\s <- match whitespace character
+ <- matches one or more times
/<- end the regex.
之後,我們會下劃線.replace(/\s+/g, "_")
然後找到並匹配所有非單詞字符替換此。
/ <- start the regex
\W <- match all non word characters (everything but a-z, A-Z, 0-9 and _)
+ <- matches one or more times
/<- end the regex
這部分看起來像這樣.replace(/\W+/g, "")
的g
/
代表全球看所有沿繩而不是隻爲第一場比賽閉幕後。
這裏有一個fiddle
"Gem. Buitentemperatuur (etmaal)".toLowerCase().replace(/[^a-z]+(?!$)/g, "_").replace(/^[^a-z]|[^a-z]$/, "");
最終取代所有的空格,大寫和特殊字符試試這個
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
function replaceAll(find, replace, str) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
使用此:
[^\w]+
而且.replace()
與_
。
工作例如:http://regex101.com/r/nN9pX7
var str = "Gem. Buitentemperatuur (etmaal)";
str.replace(/\W+/g, "_").toLowerCase().replace(/(^_|_$)/, "");
您可以使用:
s="Gem. Buitentemperatuur (etmaal)";
s.toLowerCase().replace(/ +/g, '_').replace(/\W+/g, '');
//=> "gem_buitentemperatuur_etmaal"
感謝您的詳細解釋.. – Julez