0

So I have my code like this:

for (var i = 0; i < str.length; i++) {
    str = str.replace("|", "Math.abs(");
    str = str.replace("|", ")");
}

Is there anyway to get the same effect using a regex?

Or at least a regex with a function?:

str = str.replace(/?/g, function() {?});

2 Answers 2

1

You can use this single regex replace method:

str = str.replace(/\|([^|]+)\|/g, 'Math.abs($1)');

RegEx Demo

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

Comments

1

You can match the string between |s and then replace them with whatever string you want

str[i] = str[i].replace(/\|(.*?)\|/g, "Math.abs($1)");

For example,

var str = ["|1|", "|-2|+|22 * -3|"];
for (var i = 0; i < str.length; i++) {
    str[i] = str[i].replace(/\|(.*?)\|/g, "Math.abs($1)");
}
console.log(str);
# [ 'Math.abs(1)', 'Math.abs(-2)+Math.abs(22 * -3)' ]

4 Comments

What does the [i] mean?
@Murplyx str[i] is to access the element at index i in the array.
What if there are multiple "|...|"'s like str[0] = "|-2|+|22 * -3|"
@Murplyx You simply have to include the global modifier, like in the updated example.

Your Answer

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