0

I have an input like this:

<input type="hidden" name="myName" value="John Fitzgerald          Kennedy      " />

When I read the input content using Javascript:

var myName = document.getElementsByName("myName")[0].value;

The content of myName: "John Fitzgerald Kennedy ";

How to have the content: "John Fitzgerald Kennedy "?

I have to count the fixed chars between name and surname to find the surname and split correctly two separate strings.

Thank you!

Stephan Muller
  • 27,018
  • 16
  • 85
  • 126
Andrea
  • 83
  • 1
  • 7
  • 3
    Well, it doesn't do that for me ([demo](http://jsfiddle.net/davidThomas/81Lxzjqw/)). Anything else happening on your page? – David Thomas Sep 26 '14 at 23:18
  • I'm sorry but your example help me so much to find the error: in the string of the input I have an entity like ' so the error is in the substr count because the input is a fixed size text but the entity use 5 of the positions and move the second part of the name on the left. how to take the input with an entity without convert it? – Andrea Sep 26 '14 at 23:39
  • Show an example that reproduces your actual content, show precisely what result you want/need, and then I'll try my best to help. – David Thomas Sep 26 '14 at 23:54

2 Answers2

0

You have content with multiple spaces. But if you want see it in HTML node like div you need to replace spaces with &nbsp;. But in <pre> tag you don't need in replacement.

http://jsfiddle.net/ha9pt60v/4/

// myName is "John Fitzgerald          Kennedy      "
var myName = document.getElementsByName("myName")[0].value;

// in <pre>
document.getElementById('pre').innerHTML = myName;

// in another tag
document.getElementById('my').innerHTML = myName.replace(/ /g, '&nbsp;');
dizel3d
  • 3,619
  • 1
  • 22
  • 35
  • But it's in the value of an ``, which does not collapse white-space (in general, for most HTML elements, you're right; but not in this context, unless I'm really mis-reading your answer?) – David Thomas Sep 26 '14 at 23:42
  • @DavidThomas, asker said that he lost spaces when read by `document.getElementsByName("myName")[0].value`. And I thought that he just printed it in HTML element and cannot see multiple spaces. – dizel3d Sep 26 '14 at 23:53
0

If I understand your question correctly, this may help. Try replacing spaces within the string with a single ' ' character and trimming whitespace from the beginning and end of the string like this:

var myName = document.getElementsByName("myName")[0].value.replace(/\s+/g,' ').trim();

After that you can parse the string to extract the given name and surname like this

var surname = myName.substring(myName.lastIndexOf(' '));
var givenName = myName.substring(0, myName.lastIndexOf(' '));

This link is helpful for learning about string operations: W3C String Reference

westonkd
  • 96
  • 9