从部分字符串中删除文本
Removing Text from Part of String
我需要删除不同字符串中的文本。
我需要一个函数来实现以下...
test: example1
preview: sample2
sneakpeak: model3
view: case4
...看起来像这样:
example1
sample2
model3
case4
我曾尝试使用 substr
和 substring
函数,但未能找到解决方案。
我使用了selected.substr(0, selected.indexOf(':'))
,但返回给我的只是冒号前的文本。 selected
是包含文本字符串的变量。
由于字符串的长度不同,因此也无法进行硬编码。有什么建议吗?
substring
接受两个参数:剪切的开始和剪切的结束(可选)。
substr
有两个参数:切割的起点和切割的长度(可选)。
你应该使用 substr
只有一个参数,切割的开始(省略第二个参数将使 substr
从开始索引到结束切割):
var result = selected.substr(selected.indexOf(':'));
您可能想要 trim
结果以删除结果周围的空格:
var result = selected.substr(selected.indexOf(':')).trim();
使用split函数。 split 将 return 一个数组。要删除空格,请使用 trim()
var res = "test: example1".split(':')[1].trim();
console.log(res);
试试这个:
function getNewStr(str, delimeter = ':') {
return str.substr( str.indexOf(delimeter) + 1).trim();
}
您可以使用正则表达式 /[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
我需要删除不同字符串中的文本。
我需要一个函数来实现以下...
test: example1
preview: sample2
sneakpeak: model3
view: case4
...看起来像这样:
example1
sample2
model3
case4
我曾尝试使用 substr
和 substring
函数,但未能找到解决方案。
我使用了selected.substr(0, selected.indexOf(':'))
,但返回给我的只是冒号前的文本。 selected
是包含文本字符串的变量。
由于字符串的长度不同,因此也无法进行硬编码。有什么建议吗?
substring
接受两个参数:剪切的开始和剪切的结束(可选)。
substr
有两个参数:切割的起点和切割的长度(可选)。
你应该使用 substr
只有一个参数,切割的开始(省略第二个参数将使 substr
从开始索引到结束切割):
var result = selected.substr(selected.indexOf(':'));
您可能想要 trim
结果以删除结果周围的空格:
var result = selected.substr(selected.indexOf(':')).trim();
使用split函数。 split 将 return 一个数组。要删除空格,请使用 trim()
var res = "test: example1".split(':')[1].trim();
console.log(res);
试试这个:
function getNewStr(str, delimeter = ':') {
return str.substr( str.indexOf(delimeter) + 1).trim();
}
您可以使用正则表达式 /[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