简体   繁体   中英

Regex: how do I not replace numbers?

I have a function:

export const formatScenarioName = (name) => (
  name.replace(/[^a-zA-Z ]/g, '').replace(/\s/g, '-').toLowerCase()
)

I believe this removes (white)spaces and special characters, and replaces spaces with hyphens. However it's replacing numbers as well. How do I do the opposite of that? I'd want to keep the numbers.

it should be

export const formatScenarioName = (name) => (
    name.replace(/[^a-zA-Z0-9 ]/g, '').replace(/\s/g, '-').toLowerCase()
)

but you could also use \\w instead of a-zA-Z0-9 you end up with

/[^\\w ]/g

However it includes the _ character https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

In one line:

const formatScenarioName = name => name.replace(/\W/g, '').replace(/\s/g, '-').toLowerCase()

Example:

 const formatScenarioName = name => name.replace(/\\W/g, '').replace(/\\s/g, '-').toLowerCase() var test = 'test0 . 23430v 34' console.log(formatScenarioName(test)) 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM