You'll need a regular expression and the replace function:
var str = '(a/(b1/8))*100';
alert( str.replace(/([^a-zA-Z0-9])([0-9])/g, '$1_$2') );
So, what's going on?
- The
/
's mark the beginning and end of the regular expression (the tool best suited to this task).
[^a-zA-Z0-9]
means "nothing which is a letter or a number".
[0-9]
means "a digit".
- Together, they mean, "something which is not a letter or a number followed by a digit".
- The g at the end means "find all of them".
- The
()
groups the regular expression into two parts $1 and $2
- The
'$1_$2'
is the output format.
So, the expression translates to:
Find all cases where a digit follows a non-alphanumeric. Place a '_' between the digit and the non-alphanumeric. Return the result.
Edit
As an aside, when I read the question, I had thought that the JS function was the desired answer. If that is not the case, please read rkw
's answer as that provides the C# version.
Edit 2
Bart brought up a good point that the above will fail in cases where the string starts with a number. Other languages can solve this with a negative lookbehind, but JavaScript cannot (it does not support negative lookbehinds). So, an alternate function must be used (a NaN test on substr( 0, 1 ) seems the easiest approach):
var str = '(a/(b1/8))*100';
var fin = str.replace(/([^a-zA-Z0-9])([0-9])/g, '$1_$2');
if( !isNaN( fin.substr( 0, 1 ) ) ) fin = "_" + fin;
alert( fin );