简体   繁体   中英

transform positive numbers to '+' and negative to '-' regex/javasscript

I cannot transform a string

'1,2,3,-6,10,-2'

I need result:

'+++-+-'

all negative numbers should be

'-'

and positive

'+'

my solution:

 result.replace(/-1/g, "-")
.replace(/-2/g, "-")
.replace(/-3/g, "-")
.replace(/-4/g, "-")
.replace(/-5/g, "-")
.replace(/-6/g, "-")
.replace(/-7/g, "-")
.replace(/8/g, "-")
.replace(/-9/g, "-")
.replace(/1/g, "+")
.replace(/2/g, "+")
.replace(/3/g, "+")
.replace(/4/g, "+")
.replace(/5/g, "+")
.replace(/6/g, "+")
.replace(/7/g, "+")
.replace(/8/g, "+")
.replace(/9/g, "+")

it works fine, could it be shorter?

I'd use a replacer function instead: match an optional - and numeric characters followed by an optional comma, and replace with - if the coerced number is negative, else with + :

 const input = '1,2,3,-6,10,-2'; console.log( input.replace( /(-?\\d+),?/g, (_, str) => Number(str) < 0 ? '-' : '+' ) );

If the input can contain decimal numbers as well, then add an optional non-capturing group for them:

(-?\d+(?:\.\d+)?),?

Or, without a replacer function:

 const input = '1,2,3,-6,10,-2'; console.log( input .replace(/-\\d+,?/g, '-') .replace(/\\d+,?/g, '+') );

Must is use Regex or can it be JS only? And is the string always consisting of Ints and using split using ","? Ie would it always be something like "1,-234,4,1,-124" in addition to your example?

If so, you might be able to make use of the Math.sign() function.

Again, this result doesn't use Regex, which I am not sure if that is a "MUST HAVE" requirement.

 const example = '1,2,3,-6,10,-2'; const result = example.split(',').map(d => Math.sign(d) >= 0 ? '+' : '-').join(''); console.log(result); // "+++-+-"

Split takes the ',' delimiter to turn the string into an array that we can map over, then each individual string value 'd' can have Math.sign determine if it is a positive or negative number and we are using a ternary operator to return the result '+' or '-'. The join at the end turns out new array of '+' and '-' into a string.

Again - only using JS and not Regex which might not reflect what you need.

You could split the string and check the sign.

 var string = '1,2,3,-6,10,-2', result = string .split(',') .map(v => '+-'[+(v < 0)]) .join(''); console.log(result);

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