简体   繁体   English

JavaScript修剪字符

[英]JavaScript trim character

I want to delete "()" from each value. 我想从每个值中删除“()”。 How would I do that? 我该怎么做?

var arr = ["(one)","(two)","(three)","(four)","(five)"];

for(var i = 0; i < arr.length; i++){
  console.log(arr[i]);
}

Since all the other answers are unnecessarily complicated, here's a simple one: 由于所有其他答案都不必要地复杂,因此这里有一个简单的答案:

arr = arr.map(s => s.slice(1, -1));

You can do it in-place too if you prefer; 如果愿意,也可以就地进行; the important part is .slice(1, -1) , which takes a substring starting from the character at index 1 (the second character) and ending before the last character ( -1 ). 重要的部分是.slice(1, -1) ,它从索引1的字符(第二个字符)开始,到最后一个字符( -1 )之前的子字符串。

String.prototype.slice documentation on MDN MDN上的String.prototype.slice文档

use replace 使用替换

var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++){
var x = arr[i];
x = x.replace(/[()]/g,"");
console.log(x);
}

note: 注意:
i dedited, because alexander was right 我奉命,因为亚历山大说得对


so u need to use regex, "g" for search globally, 因此您需要使用正则表达式“ g”进行全局搜索,
"[" "]" to find all character inside “ [”“]”查找其中的所有字符

var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++){
    var arrLength = arr[i].length -2;
    var shortArr = arr[i].substr(1,arrLength);
    console.log(shortArr);
}

This gets one character less on the front and back 这样前后的字符减少了一个

This matches ( followed by anything that isn't ) followed by ) . 这符合(后面没有任何东西) ,然后) Would also fail for "(test(ing)123)", (if you care) 对于"(test(ing)123)",也会失败"(test(ing)123)", (如果您愿意的话)

var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++) {
    arr[i] = arr[i].replace(/\(([^)]+)\)/g, "$1");
}

This is much more simple/faster (but arguably more brittle): 这更简单/更快(但可以说更脆弱):

var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++) {
    arr[i] = arr[i].substr(1, arr[i].length - 2);
}

这是快速的,并且无论字符串中有多少个括号都应该起作用,它将全部删除。

arr[i] = arr[i].split(/\(|\)/g).join("");

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

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