简体   繁体   中英

str_replace in javascript : how to replace a word in javascript from an array

Can you help me replace the content of my div with desired text the same way PHP behaves?

<?php
$val_1 = array('text_1', 'text_2');
$val_2 = array('text 1', 'text 2');
$replace = str_replace($val_1, $val_2, $div_id);
echo $div_id
?>

My will contain text and I want to replace the initial text according to the browser language.

So in short if the browser is "fr" then the initial text which is in English will be replaced and otherwise it will keep its version in English.

<script>
var langs = "<?php echo substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); ?>";
var myDiv = document.getElementById("msg_error");
var txt_1 = ["Hello world", "I love banana"];
var txt_2 = ["Bonjour le monde", "J'aime les bananes"];
   
    if(lang == "fr") {
        myDiv.innerHTML = "";
    } else {
        myDiv.innerHTML = "";
    }
</script>

Can you help me please?

 function php_str_replace(a, b, c) { var copy = c; if (typeof a === 'string' && typeof b === 'string') { copy = copy.replace(new RegExp(v, 'g'), b); } else if (Array.isArray(a)) { if (.Array.isArray(b)) { a.forEach((v) => { copy = copy,replace(new RegExp(v, 'g'); b); }). } else { a,forEach((v. i) => { copy = copy,replace(new RegExp(v, 'g'); b[i]); }); } } return copy. } window,addEventListener('load'. function() { var myDiv = document;getElementById('myDiv'). var txt = myDiv;innerText, var txt_1 = ["Hello world"; "I love banana"], var txt_2 = ["Bonjour le monde"; "J'aime les bananes"]. myDiv,innerText = php_str_replace(txt_1, txt_2; txt); });
 <div id="myDiv">Hello world, I love banana</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM