gpt4 book ai didi

javascript - 去除字母和数字以外的所有内容,并将句子中的空格替换为连字符

转载 作者:行者123 更新时间:2023-11-29 11:00:49 28 4
gpt4 key购买 nike

所以我正在尝试解析类似于 StackOverflow 标签工作方式的字符串。所以字母和数字是允许的,但其他一切都应该被剥离。空格也应该用连字符代替,但前提是它们在单词内部并且前面没有不允许使用的字符。

这是我现在拥有的:

label = label.trim();
label = label.toLowerCase();
label = label.replace(/[^A-Za-z0-9\s]/g,'');
label = label.replace(/ /g, '-');

这可行,但有一些注意事项,例如:

 / this. is-a %&&66 test tag    .   <-- (4 spaces here, the arrow and this text is not part of the test string)

变成:

-this-is-a66-test-tag----

预期:

this-is-a66-test-tag

我查看了这个以获得我现在拥有的:

How to remove everything but letters, numbers, space, exclamation and question mark from string?

但正如我所说,它并不能完全满足我的需求。

如何调整我的代码来满足我的需求?

最佳答案

您需要进行 2 处更改:

  • 由于您没有用第一个 replace 替换所有空格,您需要用第二个正则表达式替换所有空格字符(因此,必须用 \s,甚至更好,用 \s+ 来替换连续出现的多次),
  • 要最终去除前导/尾随连字符,请在第一次替换后使用 trim()

所以,实际的修复看起来像

var label = " / this. is-a %&&66 test tag    .   ";
label = label.replace(/[^a-z0-9\s-]/ig,'')
.trim()
.replace(/\s+/g, '-')
.toLowerCase();
console.log(label); // => this-isa-66-test-tag

请注意,如果您将 - 添加到第一个正则表达式 /[^a-z0-9\s-]/ig,您还将保留原始连字符在输出中,它看起来像当前测试用例的 this-is-a-66-test-tag

关于javascript - 去除字母和数字以外的所有内容,并将句子中的空格替换为连字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47457447/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com