user275753
user275753

Reputation: 41

javascript replace 2 characters

i would like to ask, how to replace char "(" and ")" with ""

it is because i can only replace either ( or ) with "" instead of both

how to achieve the goal??

that is

original: (abc, def)

modified: abc, def

thanks

my code:

<html>
<body>

<script type="text/javascript">

var str="(abc, def)";
document.write(str.replace("(",""));

</script>
</body>
</html>

Upvotes: 3

Views: 5062

Answers (5)

user113716
user113716

Reputation: 322502

If the parentheses will be the first and last characters, you could avoid a regular expression by using .substring().

Example: http://jsfiddle.net/nRh3C/

var string =  "(abc, def)";

alert( string.substring(1, string.length-1) );

or using .substr():

Example: http://jsfiddle.net/nRh3C/1/

var string =  "(abc, def)";

alert( string.substr(1, string.length -2) );

Upvotes: 2

Minkiele
Minkiele

Reputation: 1280

An alternative version using a single regexp is str.replace(/\(|\)/g,"");

Upvotes: 0

NVRAM
NVRAM

Reputation: 7137

Use a regexp, and the g for global replacements:

var str="(abc, def)";
document.write(str.replace(/[()]/g,''));

For reference: http://javascriptkit.com/jsref/regexp.shtml

Upvotes: 6

Nik
Nik

Reputation: 2726

You could use a regex, or

<html>
<body>

<script type="text/javascript">

var str="(abc, def)";
document.write(str.replace("(","").replace(")",""));

</script>
</body>
</html>

Upvotes: 3

Vinay B R
Vinay B R

Reputation: 8421

use str.replace(/\(/g,'').replace(/\)/g,'');

Upvotes: 1

Related Questions