2

I have a javascript array with contains a bunch of anchor elements like this:

["<a href="#" id="id1">First anchor<a>", "<a href="#" id="id2">Second anchor<a>", "<a href="#" id="id3">Third anchor<a>"]

I would like to change just the text in the last anchor element (Third anchor) while keeping the attributes of the anchor element itself unchanged (meaning I want to keep my id and href attributes intact). How would I do this and returned the changed array?

4 Answers 4

4

You don't have an array of anchor elements, you have an array of strings. And you have a big syntax error since you've tried to include double-quotes inside double-quoted strings without escaping them. Anyway:

var array = ["<a href=\"#\" id=\"id1\">First anchor<a>", "<a href=\"#\" id=\"id2\">Second anchor<a>", "<a href=\"#\" id=\"id3\">Third anchor<a>"];

array[2] = array[2].replace(/^(<[^>]+>)([^<]*)(<)/,
                            "$1" + "yourreplacementtexthere" + "$3");

Demo: http://jsfiddle.net/byQcW/

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

Comments

3

There are few syntax problems in the array related to using ' and " also the closing tag for a is wrong

array = ['<a href="#" id="id1">First anchor</a>', '<a href="#" id="id2">Second anchor</a>', '<a href="#" id="id3">Third anchor</a>'];
array[2] = array[2].replace(/(<a[^>]*?>)(.*)(<\/a>)/, '$1' + 'replacerstring' + '$3');

Comments

1

Try this:

var arr = ['<a href="#" id="id1">First anchor<a>', '<a href="#" id="id2">Second anchor<a>', '<a href="#" id="id3">Third anchor<a>']  
arr[2] = $(arr[2]).text('Your text here').prop('outerHTML');

2 Comments

Won't that change the third element from a string to an actual DOM element?
@nnnnnn Yes, it seems like it. The output of console.log does change in Chrome Dev Tools.
0

If an array of anchor tags is what you wanted, then jQuery's map method would make this trivial:

var strings = ["<a href='#' id='id1'>First anchor</a>", "<a href='#' id='id2'>Second anchor</a>", "<a href='#' id='id3'>Third anchor</a>"];

var anchor_elements = $.map(strings, function(el){
  return $(el).get();
});

You can now easily change the text of any element with jQuery:

$(anchor_elements[2]).text('New text');

Comments

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.