TDG
TDG

Reputation: 1302

Jquery - Get First character of word after space

Used below HTML & JS to get first character of string and display. Manually its possible to calculate and get value.

When its goes to dynamic and name with only first and last name not sure how to calculate character position after space and get first character of word.

$('.splitname .fname').html(name.charAt(0));
$('.splitname .mname').html(name.charAt(8));
$('.splitname .lname').html(name.charAt(16));
<div class="name">Desmond Patrick Reymond</div>

<div class="splitname">
    <span class="fname">D</span>
    <span class="mname">P</span>
    <span class="lname">R</span>
</div>

Upvotes: 0

Views: 1347

Answers (3)

PeterKA
PeterKA

Reputation: 24648

You can make use of Array#split and Array#map and Array#join as in the demo below. Result will be:

<div class="splitname">
    <span class="fname">D</span>
    <span class="mname">P</span>
    <span class="lname">R</span>
</div>

//Classes for the initials
const classes = ['fname', 'mname', 'lname'];
//Where to put the initials
$('.splitname')
    //make HTML generated content of
    .html(
        //Get Full Name
        $('.name').text()
        //Break into names array
        .split(' ')
        //Get initial of each name
        .map(name => name.charAt(0))
        //Wrap each initial in a span element
        .map((initial,index) => `<span class="${classes[index]}">${initial}</span>`)
        //Join all span elements array into string
        .join('')
    );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">Desmond Patrick Reymond</div>

<div class="splitname"></div>

Upvotes: 0

Always Helping
Always Helping

Reputation: 14570

You can simply use match() function and a simple ReGex to get the dynamic text data with spaces without having to check for charAt()

//get text
let name = $('.name').text();
//match the spaces
var matches = name.match(/\b(\w)/g); // [D,P,R]
//join the chars - if needed
var joinChar = matches.join(''); // DPR
//show the split name
$('.splitname').text(joinChar);
console.log(matches ) // [D,P,R] //Array
console.log(joinChar) //DPR //String
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">Desmond Patrick Reymond</div>
<div class="splitname"></div>

Upvotes: 0

Dennis Hackethal
Dennis Hackethal

Reputation: 14305

Use this logic:

"Desmond Patrick Reymond".split(" ").map(name => name[0])
// => ["D", "P", "R"]

If you need to modify the HTML programmatically, do:

let s = $('.name').text();
s.split(" ").map(name => $('.splitname').append(name[0]))

(It's not really good practice to use map for side effects though; you may choose to use forEach instead.)

Upvotes: 1

Related Questions