简体   繁体   中英

Javascript Regex ignore a hyphen

I need a little help in how to structure the following Regex replace. I have a string of names and I need to replace one of the names with code that wraps a bold around it. My problem is that sometimes the name is hyphenated such as Jones-Smith. Some times the hyphen is missing such as Jones Smith so if the string is

     NameString = "Green, Blue, Yellow, Jones-Smith, Pink"  

I need

   NameString ="Green, Blue, Yellow, <b>Jones-Smith</b>, Pink"

and if I have

       NameString= "Green, Blue, Yellow, Jones Smith, Pink"

I need

        NameString= "Green, Blue, Yellow, <b>Jones Smith</b>, Pink"

I could have either

       thisLastName= "Jones-Smith"

or

      thisLastName= "Jones Smith"

   

You probably don't need regex for this. Try using replace with string instead.

I'm not entirely clear on your purpose or reason for using regex rather than simply string.replace('name-to-replace') , but you could use the vertical line character for OR in regex | :

let regex = /Jones-Smith|Jones Smith/

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