How to get first character of string by Jquery or javaScript?

By : Teodor
Source: Stackoverflow.com
Question!

I have a span with inner span and I'm trying to get the first character of the inner span (t) and change its color. I tried to do that with many way with both JavaScript and jQuery and it doesn't work

// with javascript    

var index = document.getElementById('spa');
var indexsl = index.slice(0, 1);
indexsl.style.color = "f00"; //doesn't work

var index = document.getElementById('spa');
var indexsl = index.substring(0, 1);
indexsl.style.color = "f00"; //doesn't work

var index = document.getElementById('spa');
var indexsl = index.charAt(0, 1);
indexsl.style.color = "f00"; //doesn't work


// with jQuery

var index = $('.design span').charAt(0);
index.css('color', '#f00') // doesn't work

var index = $('.design span').substring(0, 1);
index.css('color', '#f00') // doesn't work

var index = $('.design span').slice(0, 1);
index.css('color', '#f00') // doesn't work
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="design">DESIGNED BY <span id="spa">Teodor Victor</span></span>

By : Teodor


Answers

What you want is charAt.

var str = 'some string';
console.log(str.charAt(0)); // return 's'


Did you try like this ?

var header = $('.design span').text().charAt(0);
index.css('color','#f00');

Or

var header = $('.design span').text().substring(0,1);
index.css('color','#f00');
By : mlbd


You can get first character, insert it with a different font color and then add rest of the content:

var span = $('.design span');
var html = span.html();

span.html("<span style='color:red;'>"+ html.charAt(0)  +"</span>" + html.substring(1,html.length));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="design">DESIGNED BY <span>Teodor Victor</span></span>

By : Marcin C.


This video can help you solving your question :)
By: admin