4

I have following string:

text = '20 as a % of 50'

I need to replace it using a regular expression, the result should be:

'20 / 50 * 100'

How can I do this?

2
  • Can you give another example? I can't get the regular pattern from this one Commented Apr 5, 2011 at 9:17
  • sounds like you're trying to hack an "are you a human" portion of a form ;) Commented Jan 30, 2016 at 19:26

2 Answers 2

4

I created an example here: http://regexr.com?2tfam

You can match with (\d+) as a % of (\d+) and replace with $1 / $2 * 100.

var a="text = '20 as a % of 50'";
alert(a.replace(/(\d+) as a % of (\d+)/, '$1 / $2 * 100'));

I also created a jsFiddle.

EDIT: If your text between the numbers will change, you can use this regex:

(\d+)[%a-zA-Z ]+(\d+)

It assumes that the operator is % and between the numbers only letters and spaces can occur.

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

1 Comment

thanks, and what if between two numbers can be chars, for example 100 usd as a % of 200 usd, and i need to keep usd in str?
0

This should help you,

var str="20 as a % of 50"; 
var patt1=/(\d)+/g;
alert(str.match(patt1)[0]+ "/"+ str.match(patt1)[1] + "* 100");

Comments

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.