0

there is a div with some values like this:

<div id="links">
<link1>||<link2>||<link3>
</div>

i know in javascript we can make an array of a string with str.split("||"); but my problem is i can't define a variable for some reasons in this case, i just need to get values of div block like a var,but i don't know how, i need something like this from above block:

var str = '<link1>||<link2>||<link3>';
2
  • Do you want a string or array of strings? Commented Jun 12, 2012 at 18:15
  • first i need a string then i need to make an array of it! so finally i need array. Commented Jun 12, 2012 at 18:22

2 Answers 2

3

Fetch the innerHTML from your div and then trim it by removing spaces at the begining and end of your string:

var str = document.getElementById('links').innerHTML.
            replace(/^\s*/, '').replace(/\s*$/, '');

Then you can go ahead and do:

var arr = str.split("||");
Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot all gays, it worked! but also i need to delete last || because my links come from a weblog system and this link system is auto, links are like this: link1||link2||link3|| please help me to solve this problem too. thank you again
@Vahid You can strip off the last || at the same time as the trailing spaces just by changing /\s*$/ to /\|\|\s*$/ :)
2

How's this?

var array = document.getElementById('links').innerHTML.trim().split('||');

If you only want a string, use this:

var str = document.getElementById('links').innerHTML.trim();

4 Comments

+1 - This is the same as my answer with the difference that it will be slightly faster on browsers that support trim but won't work on non-modern browsers without a shim.
What browsers do not support it?
Almost any browser that wasn't released in the last couple of years. The most popular browser that doesn't support it is probably IE 8.
Thanks for the catch. I was thinking 'innerHTML', but never typed it. :P

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.