[英]Regular Expression Replace in Javascript
Test 1
Test & Test 2
Test,Test 2
Test-Test2
Test/Test2
Test. Test2
Test 1 Test 2 Test 3
Test 1 Test 2 - Test 3, Test 4, Test 5
I have the following string array, I need to replace this via javascript regex to convert all of these to lowercase and separated with -
. 我有以下字符串数组,我需要通过javascript正则表达式将其替换为将所有这些转换为小写并用-
分隔。
Expected output 预期产出
test-1
test-test-2
test-test2
I have been using this till now 我一直在使用这个
link = str.replace(new RegExp("[^a-zA-Z0-9-]", "gi"), "-").toLowerCase();
link = link.replace("--", "-");
I would remove the -
from the regex, and add the +
to describe one or more of the characters to be replaced. 我将从正则表达式中删除-
并添加+
来描述要替换的一个或多个字符。
var str = "Test 1 Test 2 - Test 3, Test 4, Test 5"
var regex = new RegExp("[^a-zA-Z0-9]+", "gi");
str.replace(regex, "-").toLowerCase(); // "test-1-test-2-test-3-test-4-test-5"
Use .toLowerCase
and this regexp: /[^a-z0-9-]+/g
使用.toLowerCase
和这个正则表达式: /[^a-z0-9-]+/g
'Test & Test 2'.toLowerCase().replace(/[^a-z0-9-]+/g, '-')
#=> 'test-test-2'
+
will match 1 or more occurrences, so it'll replace all consecutive characters, and replace them with a single -
+
将匹配1个或多个匹配项,因此它将替换所有连续字符,并将其替换为单个字符-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.