简体   繁体   中英

Remove string starting with certain character

I am manipulating some content that I receive from an API. At the end of the main text field, The api sometimes returns the string below:

@@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() .

s.slice(0,s.lastIndexOf("@@canvas-link@@")); // FASTEST

Here's a jsPerf which shows them beating both RegEx and 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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