Emma Leonil Emma Leonil - 2 years ago 80
Javascript Question

Is there any way to replace text that defines a value in array using jQuery?

Here the HTML code:

<textarea>I have played arr[0] and i always try to arr[1] in my arr[2]</textarea>

Here is the array:

var arr = ["football", "drive", "city"]

How to replace
with the correct values from the array
on click to create a new
with the new content like that:

<textarea>I have played football and i always try to drive in my city</textarea>

Thanks in advance

Answer Source

You could use regex for this:

yourTextArea.value = yourTextArea.value.replace(/arr\[(.+?)\]/g, function (orig, index) {
    return arr[index];

This captures the index from the "arr[x]" strings, and uses the index to get the data from the arr array. The parentheses define a capturing group, and the .+? does the capturing itself.

It's quick and dirty :)

For reference, I stole the idea from this answer.

By the way you would be better off using an i18n library instead of hacking manually. There are a couple of gettext-like solutions for JavaScript too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download