提问人:Bibek Kshetri 提问时间:9/27/2023 最后编辑:SuleymanBibek Kshetri 更新时间:9/28/2023 访问量:65
在每个单词之后拆分字符串的正则表达式
Regular expression to split the string after every word
问:
编写此字符串以一次匹配所有测试字符串。
String="AQuickBrown_fox jump over the-lazy-Dog";
基本上我想让这些字符串看起来像这样:
"a-quick-brown-fox-jump-over-the-lazy-dog"
我在字符串上尝试了函数,并在返回的数组上应用了函数并应用了。但我找不到解决方案。我想知道可以拆分单词的正则表达式,以便我可以获得所需的字符串。split("/regex/")
join("-")
.toLowerCase()
答:
0赞
Orifjon
9/27/2023
#1
从 https://www.geeksforgeeks.org/how-to-convert-a-string-into-kebab-case-using-javascript/
这将检查空格、大写字母和下划线。它创建一个数组并推送分隔字符串的单词。现在使用 .之后,将整个字符串转换为小写。join()
const kebabCase = str => str
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.join('-')
.toLowerCase();
console.log(kebabCase('Geeks For Geeks'));
console.log(kebabCase('GeeksForGeeks'));
console.log(kebabCase('Geeks_For_Geeks'));
console.log(kebabCase('AQuickBrown_fox jump over the-lazy-Dog'));
0赞
mplungjan
9/27/2023
#2
为了提高可读性,我更喜欢多个替换
我将为此撬开烤肉串名称
const kebabCase = (str) => str
// Camelcase - handle single letters too
.replace(/([a-z])([A-Z])|([A-Z])([A-Z][a-z])/g, '$1$3-$2$4')
// non-alphanumeric characters and spaces
.replace(/[^a-z0-9]+/gi, '-')
// lowercase and trim dashes
.toLowerCase().replace(/^-|-$/g, '');
const inputString = "AQuickBrown_fox jump over the-lazy-Dog";
const outputString = kebabCase(inputString);
console.log(outputString); // "a-quick-brown-fox-jump-over-the-lazy-dog"
0赞
Hao Wu
9/27/2023
#3
下面是一个使用替换函数的解决方案:
const toKebab = text => text.replace(/[\W_]+|(?<=[A-z])(?=[A-Z])/g, '-').toLowerCase();
console.log(toKebab('AQuickBrown_fox jump over the-lazy-Dog'));
评论
"AQuickBrown_dog jump over the-lazy-Fox"