Emma Leonil Emma Leonil - 6 months ago 15
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
arr[0]
,
arr[1]
and
arr[2]
with the correct values from the array
arr
using
jQuery
on click to create a new
textarea
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

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.

Comments