繁体   English   中英

如何摆脱 JS 中的第一个特定字符串

[英]How to get rid of first specific string in JS

例如,我有一些字符串数据如下。

const a = '(@) Apple (ac)' // there is a space after ')'
const b = '(*) Com(yes)'
const c = '(ac) DC (ho)'
const d = '(%)MS' // there is no space after ')'
const e = 'yes man(ho)'

我想修改这封信如下。

const a = 'Apple (ac)'
const b = 'Com(yes)'
const c = 'DC (ho)'
const d = 'MS'
const e = 'yes man(ho)'

所以我试图用这个来做到这一点。

var res = str.substring(0, 1);

我可以得到 '(' 或者我正在考虑使用 split。

const words = str.split(();

但我不知道我怎样才能完全摆脱“(某事)”这些附加词。
如果你给我一些建议,我很感激你。 非常感谢您阅读它。

您可以使用正则表达式删除字符串开头的括号(以及可选的以下空格):

 var str = "(@) Apple (foo)"; str = str.replace(/^\\([^)]*\\)\\s*/, ""); console.log(str);

您可以使用正则表达式来实现这一点; substring不会很容易工作,因为extra部分可能存在与否,所以你需要在申请前检查它,但是这个getRidOfExtra可以完成这项工作;

正则解释:

(\\([^\\)]*\\)) => (some_charachters)模式

(\\([^\\)]*\\))? 通过添加?

\\s? 一个可选的空白字符

(.+)字符串的其余部分

这个matches[matches.length - 1]将返回最新的匹配组,即(.+)

 const a = '(@) Apple (ac)' // there is a space after ')' const b = '(*) Com(yes)' const c = '(ac) DC (ho)' const d = '(%)MS' // there is no space after ')' const e = 'yes man(ho)' function getRidOfExtra (str) { let matches = str.match(/(\\([^\\)]*\\))?\\s?(.+)/); return matches[matches.length - 1]; } console.log(getRidOfExtra(a)) console.log(getRidOfExtra(b)) console.log(getRidOfExtra(c)) console.log(getRidOfExtra(d)) console.log(getRidOfExtra(e))

你可以尝试这样做:

const a = "(@) Apple"
var res = a.substring(a.indexOf(')')+1).trim();

这将采用“)”的索引并修剪您的字符串,因此您将留下Apple

您可以使用包含捕获组的正则表达式来完成

 const getAfterParanthesis = (str) => { return /(\\(\\S*\\))?\\s?(.+)/.exec(str)[2]; }; console.log(getAfterParanthesis('(@) Apple')); console.log(getAfterParanthesis('(@) Apple (ac)')); console.log(getAfterParanthesis('(*) Com(yes)')); console.log(getAfterParanthesis('(ac) DC (ho)')); console.log(getAfterParanthesis('(%)MS')); console.log(getAfterParanthesis('yes man(ho)'));

收集数组中的所有变量并执行以下循环:

var myConsts =  = [a, b, c, d, e];

//Do this two times to remove every parenthesis.
for(var i = 0; i < 2; i++){
     myConsts.map(element => element.replace(/\(.*\)\s*/, ""));
}

暂无
暂无

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

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