简体   繁体   English

在 Javascript 中的字符串中的字符之前获取文本

[英]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.我正在尝试在 javascrip 中的字符串中获取“-”之前的文本,例如,我想从 2021 年 2 月 27 日 11:30 - 12.30 获得 2021 年 2 月 27 日 11: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"> .您在 id 属性<div id="#am-events-booking">中添加了# But you will get another issue because you are passing invalid date in Date constructor.但是您会遇到另一个问题,因为您在 Date 构造函数中传递了无效的日期。 You can fix date by replace 27th to 27您可以通过将27th日替换为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使用 Jquery text()您可以获得预期值

 $(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.该错误是因为您尝试拆分的字符串未定义,这是因为 jQuery 语法无法正确返回您期望的内容。

There are two other problems:还有两个问题:

  1. There are multiple am-event-info divs.有多个 am-event-info div。 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:我建议你一个纯 js 解决方案,我们首先识别所有 am-event-sub-info div,遍历它们,检查它们是否包含日期,如果是,则在该日期操作:

    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 dateString 转换为有效日期,这将使下面的功能代码:

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);

    }

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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