2017-09-15 49 views
2

我需要删除不同字符串中的文本。从部分字符串中删除文本

我需要的功能,这将使以下...

test: example1 
preview: sample2 
sneakpeak: model3 
view: case4 

...是这样的:

example1 
sample2 
model3 
case4 

我已经使用substrsubstring功能试过,但未能找到解决方案。

我用selected.substr(0, selected.indexOf(':')),但是所有返回给我的是冒号前的文本。 selected是包含文本字符串的变量。

由于字符串具有不同的长度,所以它不能被硬编码。有什么建议么?

回答

1

使用split函数。拆分将返回一个数组。要删除空格使用TRIM()

var res = "test: example1".split(':')[1].trim(); 
 

 
console.log(res);

+0

这个答案最适合我!谢谢! – Rataiczak24

+0

@ Rataiczak24很高兴听到 –

1

substring需要两个参数:剪切开始和剪切结束(可选)。

substr需要两个参数:剪切的开始和剪切的长度(可选)。

您应该使用substr一个参数而已,切断开始(省略了第二个参数将使从一开始的索引substr下调至月底):

var result = selected.substr(selected.indexOf(':')); 

您可能要trim结果去除结果附近的空格:

var result = selected.substr(selected.indexOf(':')).trim(); 
0

试试这个:

function getNewStr(str, delimeter = ':') { 
 

 

 
    return str.substr(str.indexOf(delimeter) + 1).trim(); 
 

 

 
}

0

你可以用正则表达式/[a-z]*:\s/gim
做参见示例代码片段低于

var string = "test: example1\n\ 
 
preview: sample2\n\ 
 
sneakpeak: model3\n\ 
 
view: case4"; 
 

 
var replace = string.replace(/[a-z]*:\s/gim, ""); 
 

 
console.log(replace);

输出将是:

example1 
sample2 
model3 
case4