如何删除所有字符串,包括连字符

时间:2017-10-11 15:09:56

标签: javascript

我在Mirth变换器中使用javascript。我为我的无知道歉,但我没有javascript培训,并且很难成功利用来自此处或其他地方的类似线程的信息。我正试图从'Room-Bed'修剪一条绳子,只是'床'。 “房间”和“床”值将波动。所有相关数据都来自ADT界面,我们的客户端在床栏中发送房间和床值,用连字符分隔,产生不必要的冗余。请帮助我提供从收到的'Room-Bed'中产生'Bed'结果所需的代码。

1 个答案:

答案 0 :(得分:0)

有很多方法可以减少你想要的字符串。您选择的将取决于您的输入和所需的输出。对于您的简单示例,一切都会奏效。但是如果你有多个连字符的字符串,它们会呈现不同的结果。它们还具有不同的性能特征。平衡它的性能与它的调用频率,以及你认为最具可读性的那些。

// Turns the string in to an array, then pops the last instance out: 'Bed'!
'Room-Bed'.split('-').pop() === 'Bed'

// Looks for the given pattern,
// replacing the match with everything after the hyphen.
'Room-Bed'.replace(/.+-(.+)/, '$1') === 'Bed'

// Finds the first index of -,
// and creates a substring based on it.
'Room-Bed'.substr('Room-Bed'.indexOf('-') + 1) === 'Bed'