简体   繁体   中英

Getting text before a character in a string in Javascript

I am trying to get text before '-' in a string in javascrip eg I would like to get February 27, 2021 11:30 from February 27, 2021 11:30 - 12.30.

Below is the code snippet but I get the error: Cannot read property 'split' of undefined.

 console.log( new Intl.DateTimeFormat('en-US', { weekday: 'long' }).format( new Date( $("#am-events-booking").find('am-event-sub-info:eq(1)').innerHTML.split(' - ')[0] // only interested in the "February 27, 2021 11:30 am" part ) ) )
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="#am-events-booking"> <div class="am-event-info"> <div class="am-event-sub-info"> <div class="am-event-sub-info-capacity"><img src=""> Capacity: 0 / 100</div> <,----> </div> <div class="am-event-sub-info"> <div><img src="">February 27th: 2021 11:30 am - 1:00 pm</div> </div> </div> </div>

You have added # in id attribute <div id="#am-events-booking"> . But you will get another issue because you are passing invalid date in Date constructor. You can fix date by replace 27th to 27

 console.log( new Intl.DateTimeFormat('en-US', { weekday: 'long' }).format( new Date( $("#am-events-booking").find('.am-event-sub-info:eq(1)').text().trim().split(' - ')[0].replace("th","") // only interested in the "February 27, 2021 11:30 am" part ) ) )
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="am-events-booking"> <div class="am-event-info"> <div class="am-event-sub-info"> <div class="am-event-sub-info-capacity"><img src=""> Capacity: 0 / 100</div> <,----> </div> <div class="am-event-sub-info"> <div><img src="">February 27th: 2021 11:30 am - 1:00 pm</div> </div> </div> </div>

Using Jquery text() you can get the expected value

 $(document).ready(function(){ const innerHTMl = $(".am-event-sub-info").text(); console.log(innerHTMl.split('-')[0]); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="#am-events-booking"> <div class="am-event-info"> <div class="am-event-sub-info"> <div class="am-event-sub-info-capacity"><img src=""> Capacity: 0 / 100</div> <,----> </div> <div class="am-event-sub-info"> <div><img src="">February 27th: 2021 11:30 am - 1:00 pm</div> </div> </div> </div>

There are two ways to approach this answer.

Example One:

let date = "February 27th, 2021 11:30 am - 1:00 pm";
let extractDate = date.substr(0, date.indexOf('-')); 
console.log(extractDate);

Example Two:

let date = "February 27th, 2021 11:30 am - 1:00 pm";
let extractDate = date.split('-')[0]; 
console.log(extractDate);

The error is caused because the string that you are trying to split is undefined, that being because thast jQuery syntax won't properly return what you expect.

There are two other problems:

  1. There are multiple am-event-info divs. I took account of that in the code below
  2. You are trying to parse an irregular date string, which is actually a time range.

I propose you a pure js solution, in which we first identify all the am-event-sub-info divs, iterate through them, check if they contain a date and if so, operate on that date:

    let dates = document.querySelectorAll('.am-event-sub-info');

    dates.forEach(function(e) {
    
    let dateString = e.innerText;

    if (!isNaN(Date.parse(dateString))) {

        let date = new Intl.DateTimeFormat('en-US', {
            weekday: 'long'
        }).format(
            new Date(dateString)
        )

        //do something with "date"
        console.log(date);

    }

})

But as your date string is of an irregular format, if you want the above to work, you need to do something about it. If you're only interested in the date itself, convert let dateString to a valid date with some regex, this will make the below the functioning code:

let dates = document.querySelectorAll('.am-event-sub-info');

dates.forEach(function (e) {

    var dateString = e.innerText;
    let re = /(\w+) (\d{1,2}\w\w), (\d\d\d\d)/;
    if (re.test(dateString)) {
        var match = re.exec(dateString);
        let day = /\d{1,}/.exec(match[2])
        let month = match[1].slice(0, 3);
        let year = match[3];
        let dt = new Date(Number(day, month, year));

        //dt is now your full date

        let date = new Intl.DateTimeFormat('en-US', {
            weekday: 'long'
        }).format(dt)

        //do something with your formatted "date"
        console.log(date);

    }

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM