2
<?php
function toconv(string)
{
 $gogo = array("a" => "b","cd" => "e");
 $string = str_replace(
 array_keys( $gogo ),
 array_values( $gogo ),
 $string
 );
 return $string;
}
?>

How can I implement that in JavaScript?

nickf
548k199 gold badges660 silver badges727 bronze badges
asked Oct 25, 2008 at 11:48

3 Answers 3

4

And to make it in a way, where you can do it directly from an array:

<script type="text/javascript">
function toconv(string){
 var gogo = {"a":"b", "cd":"e"}, reg;
 for(x in gogo) {
 reg = new RegExp(x, "g");
 string.replace(x, gogo[x]);
 }
 return string;
}
</script>
nickf
548k199 gold badges660 silver badges727 bronze badges
answered Oct 25, 2008 at 13:00
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the edit, nickf, I clearly missed the return-value !-)
2

String.replace() in Javascript receives regexes instead of strings and here's a translation. You need to append the g modifier to the regex to replace all occurrences instead of only the first one.

<script>
function toconv(str) {
 replacements = ['b','e'];
 regexes = [/a/g,/cd/g];
 for (i=0; i < regexes.length; i++) {
 str = str.replace(regexes[i],replacements[i]);
 }
 return str;
}
alert(toconv('acdacd'));
alert(toconv('foobar'));
</script>
answered Oct 25, 2008 at 11:59

Comments

-1

Convert PHP Function to JavaScript

if (preg_match('/0/', $check) || preg_match('/1/', $check) || preg_match('/2/', $check) || preg_match('/3/', $check) || preg_match('/4/', $check) || preg_match('/5/', $check) || preg_match('/6/', $check) || preg_match('/7/', $check) || preg_match('/8/', $check) || preg_match('/9/', $check))
{
 exception("personal info not allowed");
 redirect(base_url() . 'edit_profile');
}
else if ((preg_match("~\b@\b~",$check)) || (preg_match("~\b.net\b~",$check)) || (preg_match("~\b.com\b~",$check)) || (preg_match("~\b@\b~",$check)) || (preg_match("~\b.edu\b~",$check)) || (preg_match("~\b.gov\b~",$check)))
{
 exception("personal info not allowed");
 redirect(base_url() . 'edit_profile');
}
Enamul Hassan
5,47323 gold badges45 silver badges61 bronze badges
answered Oct 14, 2015 at 6:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.