所以我想取一个字符串并删除它中的所有[]以及那些[] s中的所有文本/字符,但只删除名称后面的那些字符/字符。我不确定是否应该使用正则表达式或其他方法 示例:
"Name []"` to `"Name"
"Another name [text123]"` to `"Another name"
"Yet another name [a] [] [c]"` to `"Yet another name"
"[So many names] [test] []"` to `"[So many names]"
"[TITLE] name []"` -> `"name"
"[txt2] [namez] [] a"` -> `"a"
答案 0 :(得分:1)
它会运行一些正则表达式。
示例如下
var originalStrings1 = '[So many names] [test] []';
var originalStrings2 = '[TITLE] name []';
console.log(getName(originalStrings1));
console.log(getName(originalStrings2));
function getName(str)
{
var hasName = str.replace(/\[(.*?)\]/gm, '');
var noName = str.match(/\[(.*?)\]/gm);
if(isEmpty(hasName))
{
return 'Name is: '+noName[0];
}
else
{
return 'Name is: '+hasName.replace(/^\s+|\s+$/g,'');
}
}
function isEmpty(str)
{
return str.replace(/^\s+|\s+$/g, '').length == 0;
}
答案 1 :(得分:-1)
我当然使用REGEX,更快,更强,更容易。
以下是一个工作片段:
var str = "Yet another name [a] [] [c]";
var res = str.replace(/\[.*\]/i, " ");
document.getElementById('res').innerHTML = res;

<div id="res"></div>
&#13;