简体   繁体   English

用方括号替换js

[英]replace js with square brackets

I'm hoping there is a better way to write this? 我希望有更好的方法来写这个? Removing [] square brackets are a problem to me. 删除[]方括号对我来说是一个问题。

alert(CanvasData)//images[]=Base.jpg&images[]=Frame_Clear.png&images[]=Left_Clear.png&images[]=Right_Clear.png&images[]=Lenses_Lenses-Semi-Clear.png&images[]=


var PayName = CanvasData.replace("images[]=", "");
PayName = PayName.replace(/\[.*?\]/g, '');
PayName = PayName.replace(/\&images=/g, ' ');
PayName = PayName.replace(/\.png/g, " &");
PayName = PayName.replace(/\_/g, ' ');
PayName = PayName.substring(8);//remove fist 8 character (Base.jpg)
PayName = PayName.substring(0, PayName.length - 2);//remove last 2 characters // Frame Clear & Left Clear & Right Clear & Lenses Lenses-Semi-Clear &


alert(PayName)// Frame Clear & Left Clear & Right Clear & Lenses Lenses-Semi-Clear 

Thanks 谢谢

try escaping the brackets, otherwise they take on a special meaning (define a character class) for the regular expression. 尝试转义括号,否则它们对正则表达式具有特殊含义(定义一个字符类)。

CanvasData.replace("images\[\]=", "");

You are already doing the same thing, by the way, in the second line of code in the replace section. 顺便说一下,你已经在替换部分的第二行代码中做了同样的事情。

Call replace with three global regular expressions, where the first call lists every alternate that should be replaced with nothing (ie remove all '=', and 'Base.jpg&'), the second lists alternates that should be replaced with a space ('images[]', '_', and '.png'), and the third ties up your loose ends: 使用三个全局正则表达式调用replace,其中第一个调用列出每个应该替换为什么的替换(即删除所有'='和'Base.jpg&'),第二个列出应该用空格替换的替换语句(' images []','_'和'.png'),第三个将你的松散结束:

 var PayName = CanvasData.replace(/=|Base\.jpg&/g,'')
                         .replace(/images\[\]|_|\.png/g, ' ')
                         .replace(/^\s*|\s*&\s*$/g, '');

 // => "Frame Clear & Left Clear & Right Clear & Lenses Lenses-Semi-Clear"

If the square brackets [] are always empty, you could do: 如果方括号[]总是空的,你可以这样做:

var Payname = CanvasData.split("[]").join("");

Obviously that doesn't handle the general case. 显然,这不处理一般情况。

What this does, is treat [] as a data separator, and turn the string into a parsed array -- just like parsing "1,3,6,4.5,3" except our comma is a [] . 这样做是将[]作为数据分隔符,并将字符串转换为解析数组 - 就像解析“1,3,6,4.5,3”一样,除了我们的逗号是[] Then the array formed by breaking up the string is joined back to a string, with a blank separator. 然后通过分解字符串形成的数组连接回一个带有空白分隔符的字符串。 All the [] disappear. 所有[]消失了。 But those [occupied] do not. 但那些[occupied]没有。

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

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