1

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

3
  • 1
    question is not clear Commented May 19, 2016 at 11:17
  • 1
    you can use this in jQuery but question is not clear $.each(arr,function(i,v) { }); Commented May 19, 2016 at 11:18
  • Thanks for trying to help. I'm now checking your answer. I have edited the question to be clear. Commented May 19, 2016 at 12:31

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

This of course would also replace apiratesaysarr[ because that's just what they say :-].
Of course, proper sanitation is missing from the answer.
Thanks for trying to help. I'm now checking your answer. I have edited the question to be clear.
@h2ooooooo apiratesay arrr not arr :]
@EmmaLeonil My originality wasn't at it's top point with that comment. I was too lazy to google "words that end in arr" :-)

Your Answer

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.