javascript在字符前获取字符串 [英] javascript get string before a character

查看:81
本文介绍了javascript在字符前获取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,我试图在引用之前提取字符。

I have a string that and I am trying to extract the characters before the quote.

示例是从 14 > 14' - €14.99

Example is extract the 14 from 14' - €14.99

我正在使用以下代码来实现此目的。

I am using the follwing code to acheive this.

$menuItem.text().match(/[^']*/)[0]

我的问题是,如果字符串是€0.88,我希望得到一个空字符串返回。但是我收回了€0.88的全部字符串。

My problem is that if the string is something like €0.88 I wish to get an empty string returned. However I get back the full string of €0.88.

我在比赛中做错了什么?

What I am I doing wrong with the match?

推荐答案

这是你应该用来分割的东西:

This is the what you should use to split:

string.slice(0, string.indexOf("'"));

然后处理不存在的价值边缘情况:

And then to handle your non existant value edge case:

function split(str) {
 var i = str.indexOf("'");

 if(i > 0)
  return  str.slice(0, i);
 else
  return "";     
}

JsFiddle上的演示

这篇关于javascript在字符前获取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆