简体   繁体   中英

Javascript regex: replace letters near any number

I have a string:

F1 F#1 F2 F#2

I want to convert it to:

f1 F1 f2 F2

Numbers near f/F can be 0 to 9

Is it possible to do this with regex? Thanks you!

Use the following:

str = str.replace(/#/g, "");

See DEMO

You can do this using back-references. Putting parentheses around sections of your regular expression allows you to reference them in a return function (in order from left to right).

The following code works like you specified, first by changing the instances without # to lower case, then using a second regex to replace the ones with #s.

a = "F1 F#1 F2 F#2";
b = a.replace(/([A-Za-z])([0-9])/g,function(match,$1,$2,original){return $1.toLowerCase() + $2;}).replace(/([A-Za-z])#([0-9])/g,"$1$2");
//b = f1 F1 f2 F2

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