在出现空格时拆分一个字符串

时间:2021-01-25 19:41:44

I have strings like "test-example - one" I need to get the characters before the space. I can split it using

我有像“test-example - one”这样的字符串我需要在空格之前获取字符。我可以用它拆分它

this.value.substring(0, this.value.indexOf('-')

but it won't work if I substitute a ' ' for the '-'

但如果我用''代替' - '它就行不通

1 个解决方案

#1


0  

Are you returning the result of substring() to a variable? If I run this, it returns what was expected...

你是否将substring()的结果返回给变量?如果我运行它,它返回预期的...

var s = 'test-example - one';
var s2 = s.substring(0, s.indexOf(' '));
console.log(s2);

https://jsfiddle.net/zg6x7ywt/

#1


0  

Are you returning the result of substring() to a variable? If I run this, it returns what was expected...

你是否将substring()的结果返回给变量?如果我运行它,它返回预期的...

var s = 'test-example - one';
var s2 = s.substring(0, s.indexOf(' '));
console.log(s2);

https://jsfiddle.net/zg6x7ywt/