Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select text string before comma, set it to uppercase

JS Fiddle Example

OK--I have a field that is a full name (last name, first name). The data that is returning isn't last and first name, it is full name. It is then printed last, first. I want to select just the last name (everything before comma), and set it to uppercase.

I may be mixing jQuery and javascript in my example, I'm not positive--still a newb. However, what I've done in the example is to:

function splitLastName(){
var splitNameArray = $('[data-dojo-attach-point|="physcianNameNode"]').split(",");
var lastName = splitNameArray[0];
var firstName = splitNameArray[1];
lastName.wrap('<span class="isUppercase" />');
}​

Basically, I'm setting a variable of the field--I've tested that it accurately grabs the element I want it to grab. I'm turning the string into an array, split by the comma field. Then setting the two parts of the array as their own variables. Finally, attempting to wrap the lastName string in a span that adds the 'isUppercase' class. I know I'm doing something wrong, what is it?

like image 809
Mike Earley Avatar asked Nov 20 '25 13:11

Mike Earley


2 Answers

function splitLastName(){
    $('[data-dojo-attach-point|="physcianNameNode"]').html(function(i, v) {
        var names = v.split(',');
        return '<span class="isUppercase">'  +names[0] + '</span>,' + names[1];
    });
}

Fiddle

.html() docs


The above is a quick solution setting a new innerHTML to the element. If you want to use proper DOM manipulation, it'd be like:

function splitLastName() {
    $('[data-dojo-attach-point|="physcianNameNode"]').each(function() {
        var names = $(this).text().split(',');
        $(this).empty().append($('<span>', {
            'class': 'isUppercase',
            text: names[0]
        }), ',' + names[1]);
    });
}

Fiddle

Note that I'm using .each() so the code above will work regardless of $('[data-dojo-attach-point|="physcianNameNode"]') matching multiple elements or just a single one.

like image 56
Fabrício Matté Avatar answered Nov 23 '25 02:11

Fabrício Matté


The problem is you are trying to split a JQuery object.

I have updated your example: See here

function splitLastName(){
    var element = $('[data-dojo-attach-point|="physcianNameNode"]');//find the element
    var html = element.html();//get the contents of the DIV element

    var splitNameArray = html.split(",");//Split the value with comma
    var lastName = splitNameArray[0];//store the last name
    var firstName = splitNameArray[1];//store the first name

    var newHtml = '<span class="isUppercase">' + lastName + '</span>, ' + firstName;//create the new html using the parsed values
    element.html(newHtml);//assign the new html to the original DIV element (overwriting the old)
}
like image 38
musefan Avatar answered Nov 23 '25 02:11

musefan