2

I have:

var foo = '(bar)'
foo.replace('(', '').replace(')', '')

So, I get bar without parentheses, is there a better way to do this?

0

3 Answers 3

7

You could use:

foo = foo.replace(/[()]/g, '');

That involves a simple regular expression that matches all instances of either open- or close-parentheses. Note that you have to include that assignment, as ".replace()" does not modify the string; it returns the modified string.

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

Comments

2

You could use a regex capturing everything inside parentheses in a capturing group as per Javascrip Regex e.g.

var foo = "(bar)";
var replacedStr = foo.replace(/\((.*)\)/g, "$1");

or replacing just the parentheses with empty string e.g.

var foo = "(bar)";
var replacedStr = foo.replace(/[()]/g, ""); 

Comments

0

If it is always the first and last characters you are trying to get rid of, you could use the slice method: http://www.w3schools.com/jsref/jsref_slice_string.asp

​var foo = '(bar)';
alert(foo.slice(​​​​​​​​1, 4));
//Or
alert(foo.slice(1, foo.length - 1));​

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.