简体   繁体   中英

Issue splitting string with jQuery/Javascript if there is only one word or no space in the string

I'm using .split to extract only the first name from a string which usually has a first and last name. This works great as long as there is a space present in the string (ie first and last names), but when there is only a first name, I get the whole string doubled.

Example:

I have a string which contains the name "John Smith". When I use the code below, it returns "John". Great! But if the string is just "John" and the code is used, "JohnJohn" is returned. NO!

With this line, the js will return 'John'

<p>Name: <span class="vName">John Smith</span></p> 

With this line, the js will return 'JohnJohn'

<p>Name: <span class="vName">John</span></p>

And the script:

<script>
var designerName = $('.vName').text();
designerName = designerName.split(" ")[0];
</script>

Here it is on jsfiddle and it works fine there using same jQuery version (v1.8.2): http://jsfiddle.net/5yrYj/1

Running Chrome Version 26.0.1410.64 m. I don't understand why it wouldn't be working in my script.

Here's the full function:

function saveDesign(){
var shaftRender = $('#shaft-image-md').attr('class');
var gripRender = $('#grip-image-md').attr('class');
var labelRender = $('#label-image-md').attr('class');

gripRender = gripRender.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});
labelRender = labelRender.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});

var designerShaft = shaftRender+gripRender+labelRender;
var designerName = $('.vName').text();

//Grab only first name
designerName = designerName.split(" ")[0];
//if((/ /).test(designerName)){ designerName = designerName.split(" ")[0]; }
//designerName = (/ /).test(designerName) ? designerName.split(" ")[0]
                                    //: designerName;

$.post("saveDesign.php",
{
  name: designerName,
  shaft: designerShaft,
});

//Debug
alert(designerName); //This displays "JohnJohn"
}

No matter which of the three .split lines I use, I still get the double name if the original designerName string does not have a last name = a space. And the alert will display 'JohnJohn' at that point too.

So, how can I call the .split code ONLY if there is a space in the string? Or is there another solution which is better suited for my purpose? Any help would be very much appreciated.

Thanks.

RESOLVED: There was an extra instance of .vName in the html. Removed and now working as it should. Thanks to Francisco Afonso for proposing that was the issue.

Use indexOf or some other function that first checks if a space exists in the string. Check if all browsers support it though, as indexOf might not work with IE8 or below.

if (myvar.indexOf(' ') !== -1) {
    myvar = myvar.split(' ')[0];
} else {
    //No space so ignore...
}

This isn't jQuery and it doesn't have to be. jQuery is a great framework and I recommend it for most projects, but try and use native JavaScript whenever you can. It's generally faster and you can learn more about the language behind jQuery.

If you really want to use jQuery, you might want to try $.inArray() to check if your split worked.

This simple (pure javascript) cross-browser line calls 'the .split code ONLY if there is a space in the string' (like you asked):

if((/ /).test(designerName)){ designerName = designerName.split(" ")[0]; }

OR:

designerName = (/ /).test(designerName) ? designerName.split(" ")[0]
                                        : designerName;

It is a ternary if statement (syntax: (test) ? true : false; ), where test returns true or false when it tests the string referenced by designerName on the regex / / (one space).
Example jsfiddle here .

You're consuming text value from all elements with class = vName. You have two elements with that class so you're consuming a concatenation of their values. So: "JohnJohn Smith" And there is the bug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM