How do I use a Regex to replace non-alphanumeric c

2020-04-20 09:03发布

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]/);
}  

标签: javascript
1条回答
家丑人穷心不美
2楼-- · 2020-04-20 09:34

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);

查看更多
登录 后发表回答