How do I use a Regex to replace non-alphanumeric characters with white space?

后端 未结 1 1686
Happy的楠姐
Happy的楠姐 2021-01-24 04:38

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\".

1条回答
  •  爱一瞬间的悲伤
    2021-01-24 05:40

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

    0 讨论(0)
提交回复
热议问题