简体   繁体   English

如何获取特殊字符前的子字符串?

[英]How to get sub string before special character?

Below code is giving me expected result "1524587" but right side could be -0 , -1 etc , so how to grab left side string before - ? 下面的代码给了我预期的结果“ 1524587”,但右侧可能是-0-1等,因此如何在-之前获取左侧字符串? my 2nd option is not returning the left string 我的第二个选择不返回左字符串

main.js main.js

const str = "1524587-0";
// 1st option 
const rxNumber = element.str .replace('-0', '');

// 2nd Option 
const  splitstring = str.split('-')

You can split using using the character - and then getting the first array value of the result : 您可以使用以下字符进行分割-然后获取结果的第一个数组值:

 var str = "1524587-0".split('-'); console.log(str[0]); 

Using the same logic you'd use words[1] to get the right side of the string : 使用相同的逻辑,您将使用words[1]来获得字符串的右侧:

 var str = "1524587-0".split('-'); console.log(str[1]); 

In short , this function splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split. 简而言之 ,此函数通过使用指定的分隔符字符串确定将每个字符串拆分为多个子字符串的方式,将一个字符串对象拆分为一个字符串数组。

You can use a regex as well 您也可以使用正则表达式

/[^-]*/.exec("1524587-0")[0]

or split 或分裂

"1524587-0".split('-')[0]

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

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