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 -
.
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
'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 -
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.