[英]Remove string starting with certain character
I am manipulating some content that I receive from an API. 我正在处理从API收到的一些内容。 At the end of the main text field, The api sometimes returns the string below:
在主文本字段的末尾,api有时返回以下字符串:
@@canvas-link@@{"type":"doc","fileName":"xyzv2.jpg","fileExt":"jpg",
"fileSize":"232352",
"file":"405957767101","downloadUrl":"dummytext"}
What is the best way to remove this string from the main text field? 从主文本字段中删除此字符串的最佳方法是什么?
str = str.replace(/@@canvas-link@@.*/, '');
If you're sure it's at the end, this version is fastest ; 如果您确定最终版本是最快的 ,
s.substring(0, s.lastIndexOf("@@canvas-link@@")) ; // FASTER than most
but updated Just for fun, I've another variant using slice()
which is slightly faster in this test even than substring()
. 但已更新,只是为了好玩,我还有另一个使用
slice()
变体,它在此测试中甚至比substring()
还要快。
s.slice(0,s.lastIndexOf("@@canvas-link@@")); // FASTEST
Here's a jsPerf which shows them beating both RegEx and split. 这是一个jsPerf ,显示了它们击败了RegEx和split。 Although I'm surprised split wasn't quicker.
尽管我感到惊讶,拆分并不快。
However, your mileage may vary, and for more complex scenarios I'd expect RegEx (replace) to come out on top. 但是,您的行驶里程可能会有所不同,对于更复杂的情况,我希望RegEx(替代)能脱颖而出。
Improving Joseph Silbers, 改善约瑟夫·西尔伯斯,
str = str.replace(/@@canvas-link@@{.*}/, '');
To make sure it doesn't remove anything after. 为了确保它之后不会删除任何东西。
You could use a regular expression, but a split()
will avoid complications with carriage returns. 您可以使用正则表达式,但是
split()
可以避免回车带来的麻烦。
var str = 'foobar@@canvas-link@@{"type":"doc","fileName":"xyzv2.jpg","fileExt":"jpg",
"fileSize":"232352",
"file":"405957767101","downloadUrl":"dummytext"}';
var data = str.split('@@canvas-link@@')[0];
console.log(data);
>> foobar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.