4

I know it should be simple, and yes i've tested on online regex sites, but i just can't get this to work.

Input string: "w_(number from 1-99),h_(number from 1-99)", e.g: "w_34,h_34"

Expected Output: number replaced, e.g "w_50,h_50"

Test:

'w_34,h_34'.replace('w_[1-9][0-9],h_[1-9][0-9]', 'w_50,h_50')

But it just returns the original string. (w_34,h_34)

1 Answer 1

6

You need to use a regular expression to take advantage of the regexp syntax

'w_34,h_34'.replace(/w_[1-9][0-9]?,h_[1-9][0-9]?/, 'w_50,h_50')

This will solve to only 2 digits of numbers. An alternative would be to use the * operator.

'w_34,h_34'.replace(/w_[1-9][0-9]*,h_[1-9][0-9]*/, 'w_50,h_50')

Which would allow n-length numbers to match.

Sign up to request clarification or add additional context in comments.

4 Comments

A more flexible number match would be [1-9][0-9]*. Handles anything from 1 onwards
@Phil I opted to use the ? optional operator instead of the * 0 or more.
@Gabriel But that limits you to numbers between 1 and 99
@Phil yeah I know. It seemed in line with the OP's intentions, though there is technically very little difference in performance. I will add the other alternative and explain the diff in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.