Are you first timer at lazacode.org? Why not join us and start exchange your programming knowledge with everyone. Register today!

jQuery .substr() method

0 votes
30 views
added Mar 30 in jQuery by theoh_lee Corporal (810 points)
edited Apr 2 by LC Marshal

Get substring before specific character. In this example, we want to get '1345 albany street' text only from div.address-div before the comma 

<div class="address-div">1345 albany street, Bellevue WA 42344</div>

jQuery

var addy = $('.address-div').text();
var streetaddress= addy.substr(0, addy.indexOf(',')); 

4 Responses

0 votes
responded Apr 26 by LC Marshal Lieutenant (13,570 points)

First word selector in element

$('div.message').each(function() {
   var html = $(this).html();
   var word = html.substr(0, html.indexOf(" "));
   var rest = html.substr(html.indexOf(" "));
   $(this).html(rest).prepend($("<span/>").html(word).addClass("em"));
});
0 votes
responded May 2 by LC Marshal Lieutenant (13,570 points)

Change URL by getting last part of URL and combined a few variables to get final URL

var catName = $('.forum-category > a'), 
    catUrl = $(location).attr('href'),
    urlParts = catUrl.split("/"),
    endUrl = urlParts[urlParts.length-2],
    forumPage = '/property-forum/',
    resultUrl = forumPage + endUrl;
    // alert(endUrl);

$(catName).attr('href', resultUrl);
0 votes
responded May 2 by LC Marshal Lieutenant (13,570 points)
edited 2 days ago by LC Marshal

Get last-child of breadcrumb and use .trim to manipulate URL

var areaname = $('h1.page-header').text(),
    lookforstate = $('ol.breadcrumb li:last-child').text(),
    trimstate = lookforstate.split(","),
    resultstate  = trimstate [trimstate.length-1],
    getstate = $.trim(resultstate),
    w = "/map-search-property?&state=",
    x = "&district="; 
    result = w + getstate + x + areaname;

$('a#search-listing-area').attr('href', result);
0 votes
responded Jun 27 by birdygeek Sergeant (2,060 points)
//jQuery to wrap the first word of each paragraph with a <span> tag.
$(function() {
    $('#content p').each(function() {
        var text = this.innerHTML;
        var firstSpaceIndex = text.indexOf(" ");
        if (firstSpaceIndex > 0) {
            var substrBefore = text.substring(0,firstSpaceIndex);
            var substrAfter = text.substring(firstSpaceIndex, text.length)
            var newText = '<span class="firstWord">' + substrBefore + '</span>' + substrAfter;
            this.innerHTML = newText;
        } else {
            this.innerHTML = '<span class="firstWord">' + text + '</span>';
        }
    });
});
lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...