简体   繁体   English

删除以某些字符开头的字符串

[英]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.

相关问题 如何从某个字符串开始删除localStorage数据? - How to remove localStorage data starting with a certain string? 从字符串中删除以某个字符开头的单词 - Remove word from string beginning with a certain character 如何在javascript中删除字符串末尾的某个字符 - how to remove a certain character at the end of the string in javascript 从字符串中删除特定字符并返回到数组中 - Remove certain character from string and return into an array 匹配以 : 字符开头但不以 \\ 开头的字符串: - Match a string starting with : character, but not starting with \: 正则表达式从某个字符开始提取字符串而不包含该字符本身 - Regular expression to extract the string starting from a certain character without that character itself 如何从Javascript中的字符串中删除以某个字符开头的单词 - How to remove a word that starts with a certain character from a string in Javascript 删除字符串中某个字符之后的所有内容,但保留在标签中 - Remove everything after a certain character in a string but keep wrapped in tag 使用JavaScript删除字符串中某些字符之后的所有内容 - Remove Everything After Certain Character Within String Using JavaScript 是否可以删除某个字符留下的整个字符串 - Is it possible to remove a whole string that is left from a certain character
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM