0
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("--", "-");
3
  • Try adding \n in your character class [^a-zA-Z0-9\n-] Commented May 31, 2013 at 17:27
  • The last line of the expected output shouldn't have a - before the 2? Is that correct? If so, how are you distinguishing it from the first line? Commented May 31, 2013 at 17:33
  • I mentioned these are separate strings. Commented May 31, 2013 at 17:46

2 Answers 2

2

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"
Sign up to request clarification or add additional context in comments.

Comments

0

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 -

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.