How do I select a character using jQuery or Javascript?

How can I select a character in an HTML element with Javascript or jQuery

For example, I want to select the first or second or third "]" carchter in <p>

<p> Lorem Ipsum is simply dummy [text] of [the] printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, </p>


And when I write for example console.log (character1) it will give me the first ] in the paragraph I am doing

The order of the character is important to me because I want to change the first ']' with something else


source to share

3 answers

Try using it String.prototype.replace()

, increase the counter to select the second "A" anyway

var index = null;
var arr = $("p").text().replace(/a/ig, function (m, i) {
    return index === 2 ?  "QQQ" : m



I understand that you need to manipulate a specific element in HTML using javascript

var x = document.getElementsByTagName("p");


this will give you a list of all nodes marked with "p", you can choose yours by specifying its index

y = x[*tag index*]


then you can do:

firstIndex = y.innerHTML.indexOf("A");


or optional, if you want to get the second (or third) index of the letter, you just need to put the starting point where the index will start looking, so presumably we want to get the second index "A" and we already got the first index from the above line of code, we could do:

secondIndex = y.innerHTML.indexOf("A", firstIndex);




Ok you can do something like this

function getIndicesOf(searchStr, str, caseSensitive) {
    var startIndex = 0, searchStrLen = searchStr.length;
    var index, indices = [];
    if (!caseSensitive) {
        str = str.toLowerCase();
        searchStr = searchStr.toLowerCase();
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        startIndex = index + searchStrLen;
    return indices;

function replaceCharacter(text ,char, withChar, index) {
    var indices = getIndicesOf(text, char, true);
    return (text.substr(0, indices[index-1]) + 'withChar' + s.substr(indices[index-1]+withChar.length));

var text = 'Aekwwewj fkjkwefhwA wkejqwkjeqkwjeA A ewqeqw';
text = replaceCharacter(text, 'A', 'W', 2);





All Articles