|
-
May 21st, 2002, 04:45 AM
#1
Thread Starter
Hyperactive Member
replace all
How can I replace A With B in the string:
I used this JavaScript code:
var Y=X.replace('A','B');
but it is replace one letter only from the string ... I want to replace all A with B.
-
May 21st, 2002, 04:51 AM
#2
Addicted Member
Code:
<html>
<head>
<title>Untitled</title>
<script>
function foo(inStr) {
inStr = inStr.replace(/a/gi, 'b');
alert(inStr);
}
</script>
</head>
<body>
<input type="button" value="Test" onClick="foo('abc abc abc');">
</body>
</html>
-
May 21st, 2002, 04:55 AM
#3
Hyperactive Member
As with the previous question about match() you need to use a regex with replace().
eg:
Code:
var my_string = "abbAa";
my_string.replace(/a/, 'b');
//mystring now equals "bbbAa"
however this will only replace on occurence of a lower case 'a'
so you need to use two regex commands
g - global replace, replaces all occurence of the regex in the string.
i - ignor case, replaces upper and lowercase
so the finished statement should be:
Code:
var my_string = "abbAa";
my_string.replace(/a/gi, 'b');
//mystring now equals "bbbbb"
I recommend you get yourself a good regex book as they are invaluable in many web scripting languages such as Perl, PHP, and javascript and the syntax is very similar for all.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|