1

I built a Javascript function to make the first letter uppercase. My issue is that I have some words which are like "name_something" and what I want is "Name Something".

I did this:

function toCamelCase(text) {
  return text.replace(/\b(\w)/g, function (match, capture) {
    return capture.toUpperCase();
  }).split(/[^a-zA-Z]/);
}  
1
  • So, what went wrong? What is the question? Commented Apr 12, 2018 at 12:40

1 Answer 1

4

You can use [\W_] to get rid of characters that are not alphanumeric. Where W represent characters from a-z, A-Z and 0-9

var str = 'this $is a _test@#$%';
str = str.replace(/[\W_]+/g,' ');
console.log(str);

So, to make the words capitalise alongside the replace you can do,

var str = 'this $is a _test@#$%';
str = str.replace(/[\W_]+/g,' ');
var res = str.split(' ').map((s) => s.charAt(0).toUpperCase() + s.substr(1)).join(' ');
console.log(res);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks could you please show me in my case how that will be? I have some issues to adapt it to my
@Jakub check the working snippet. The second one replaces and change to uppercase

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.