The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
> JavaScript split word in half
Terminator
post May 14 2016, 06:03 PM
Post #1


Advanced Member
****

Group: Members
Posts: 218
Joined: 19-March 15
Member No.: 22,398



I wrote a function to split a string in half and want to make sure that I went about this the best method.

In this case, the string is always 1 word with no spaces, as I remove all spaces with Regex.

CODE

function splitString(str) {
    var middle = Math.ceil(str.length / 2);
    var s1 = str.slice(0, middle);
    var s2 = str.slice(middle);
    return s1 + " " + s2;
};


For odd amount of letters like Treat it displays with the larger amount in s1:
Split String: Tre at

Even amount of letters works correctly:
Split String: Tre ats

Does this code look good or do you suggest something different?
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post May 14 2016, 07:30 PM
Post #2


.
********

Group: WDG Moderators
Posts: 8,505
Joined: 10-August 06
Member No.: 7



It won't work if str contains HTML entities, or if str is not of type String (say type Number). None of that should happen if a user types text in a text field, though.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Terminator
post May 14 2016, 09:42 PM
Post #3


Advanced Member
****

Group: Members
Posts: 218
Joined: 19-March 15
Member No.: 22,398



Besides stripping out spaces with regex this one also strips out anything that is not a lower or uppercase letter, so no need to worry about numbers or symbols being typed in.

I was just wondering if I did it right since I came up with this on my own, but it seems to be correct. I guess I am getting better at programming.

This post has been edited by Terminator: May 14 2016, 09:56 PM
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post May 15 2016, 06:15 AM
Post #4


.
********

Group: WDG Moderators
Posts: 8,505
Joined: 10-August 06
Member No.: 7



Looks good to me. Just be careful when naming functions and variables, to avoid name collisions.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 



- Lo-Fi Version Time is now: 9th August 2020 - 04:03 PM