【问题标题】:What is the best way to split the string in typescript在打字稿中拆分字符串的最佳方法是什么
【发布时间】:2018-07-27 01:15:14
【问题描述】:

我有类似的字符串输入

输入 text: string = "今天的午餐 200 #hotelname"

输出 主题:“今天的午餐” 价格:200 标签:#酒店名称

我的解决方案是

text: string = "today lunch 200 #hotelname"
  tag: string;
  price: string;
  subject: string;

 this.text.forEach(x => {
      if(this.reg.test(x)){
         this.tag= x;
      }else if(parseInt(x)){
          this.price = x;
      }
      else{
        this.subject= x;
      }
    });
 console.log(this.subject, this.tag, this.price);

但问题是我的解决方案不能满足所有测试用例是否有使用打字稿或javascript的更好解决方案

测试用例

  1. 字符串不能有两个 no
    前 1:今天午餐 200 #hotel 200
    ex 2: 200 食物 2 0 1 #pasta
  2. 以#开头的文本被视为标签,不能在一个标签中有多个标签
    字符串
  3. 如果字符串类似于“xyz hotel 100 的食物#chinies
    输出:主题:“xyz酒店的食物” 价格:100 标签:#chinies

【问题讨论】:

  • Stack Overflow 不是代码编写服务,请分享您自己尝试过的内容。在这里提问之前,您应该做一些研究。
  • 最快的方法是自己写,而不是等待某个慷慨的傻瓜为你写,因为你不知道要等多久

标签: javascript arrays string typescript split


【解决方案1】:

使用match:

let string = "today lunch 200 #hotelname";

console.log(string.match(/(.*)\s+(\d+)\s+(#.*)/))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 2021-03-18
    相关资源
    最近更新 更多