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?
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.
str = str.replace(/##canvas-link##.*/, '');
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
Related
I have been working with Discord.js and Node to a quick bot to look up something. I need a way to find all the occurrences that appear between two square brackers and store them in an array of strings. For now I'm using string-split() with some regex, but I am unsure of the regex to use.
I have tried using a few different ones, including /[^\[\[]+(?=\]\])/g and \[\[(.*?)\]\] - I dont mind having the actual brackets in the results, I can remove them manually with string.replace().
I am also working on a fallback with the normal string.split() and other string functions, not relying on regex, but I'm still curious about a possible regex version.
The result with the first regex is totally incorrect. For example, if I try "does [[this]] work [at all]?" the output is "[[]]" and "[at all]", when it really shouldn't take the "at all", but it shouls show the "[[this]]".
With the second regex I get somewhat closer, it gives back "this"(correct) and "[at all]" (again, it shouldn't take the "at all").
I don't mind having the brackets in the output, I can remove them manually myself, but I need to find all occurrences that are specifically between two brackets.
Try this regex:
\[\[([^[\]]|(?R))*\]\]
What you are trying to do is called Matching Balanced Constructs. More info at the link.
Upon further testing, unfortunately JS does not support (?R) so this becomes far more difficult. You could use the XRegExp.matchRecursive addon from the XRegExp package.
And your expression \[\[(.*?)\]\] should work. Working example below.
var str = 'does [[this]] work [at all] with another double [[here]]?';
var result = str.match(/\[\[(.*?)\]\]/g);
var newDiv = document.createElement("div");
newDiv.innerHTML = result;
document.body.appendChild(newDiv);
Try my solution
var str = "does [[this]] work [at all]?";
var regexp = /\[([a-z0-9\s]+)\]/ig;
var resultArray = str.match(regexp);
resultArray = resultArray.map((item) => {
return item.replace(/(\[|\])/g, "");
})
console.log(resultArray);
in vb6 there was a very handy function for string manipulation which could put a character at a certain position of another string and i'm looking for an extended jquery equivalent.
let's say i'm having this string:
var mystring = "__1__";
when applying the function:
var mystring = mid(mystring,4,"x");
it should return __1x_
another example:
var mystring = "";
var mystring = mid(mystring,5,"x");
should return: ____5
i know it requires string manipulation using substr but i was wondering if there's a more elegant way?
thanks
This can be simulated in several ways although there is no such specific function (splice is standard only on Arrays, not Strings).
The easiest one-expression way I know of is with a String.replace when adding to a location "past the end of the string" is not required. Of course String.slice is also a perfectly valid approach, and may be arguably easier to understand.
mystring = "__1__"
// where 3 represents the "characters to skip before inserting"
// and 1 represents the "number of characters to replace"
midstr = mystring.replace(/([^]{3})[^]{0,1}/, "$1x")
Neither the above nor a basic slice will work like the 2nd example without additional prepend-as-needed logic.
I've a string done like this: "http://something.org/dom/My_happy_dog_%28is%29cool!"
How can I remove all the initial domain, the multiple underscore and the percentage stuff?
For now I'm just doing some multiple replace, like
str = str.replace("http://something.org/dom/","");
str = str.replace("_%28"," ");
and go on, but it's really ugly.. any help?
Thanks!
EDIT:
the exact input would be "My happy dog is cool!" so I would like to get rid of the initial address and remove the underscores and percentage and put the spaces in the right place!
The problem is that trying to put a regex on Chrome "something goes wrong". Is it a problem of Chrome or my regex?
I'd suggest:
var str = "http://something.org/dom/My_happy_dog_%28is%29cool!";
str.substring(str.lastIndexOf('/')+1).replace(/(_)|(%\d{2,})/g,' ');
JS Fiddle demo.
The reason I took this approach is that RegEx is fairly expensive, and is often tricky to fine tune to the point where edge-cases become less troublesome; so I opted to use simple string manipulation to reduce the RegEx work.
Effectively the above creates a substring of the given str variable, from the index point of the lastIndexOf('/') (which does exactly what you'd expect) and adding 1 to that so the substring is from the point after the / not before it.
The regex: (_) matches the underscores, the | just serves as an or operator and the (%\d{2,}) serves to match digit characters that occur twice in succession and follow a % sign.
The parentheses surrounding each part of the regex around the |, serve to identify matching groups, which are used to identify what parts should be replaced by the ' ' (single-space) string in the second of the arguments passed to replace().
References:
lastIndexOf().
replace().
substring().
You can use unescape to decode the percentages:
str = unescape("http://something.org/dom/My_happy_dog_%28is%29cool!")
str = str.replace("http://something.org/dom/","");
Maybe you could use a regular expression to pull out what you need, rather than getting rid of what you don't want. What is it you are trying to keep?
You can also chain them together as in:
str.replace("http://something.org/dom/", "").replace("something else", "");
You haven't defined the problem very exactly. To get rid of all stretches of characters ending in %<digit><digit> you'd say
var re = /.*%\d\d/g;
var str = str.replace(re, "");
ok, if you want to replace all that stuff I think that you would need something like this:
/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g
test
var string = "http://something.org/dom/My_happy_dog_%28is%29cool!";
string = string.replace(/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g,"");
I have this string here:
<br><br>|Me-Foo|: htht
What i want to do is to transform it to this:
<br><br>Me: htht
basically to change only the part inside the two "|", remembering tha the "Foo" might change with another name, like "john" or whatever.
.. But I don't know how to!? A quick solution anyone?
Thanks
You can remove that with...
str = str.replace(/\|(\w+)-\w+\|/, '$1');
You didn't specify the constraints of what appears between the pipes. If word characters (\w) aren't flexible enough, adjust as required.
You can easily achieve this with combination of indexOf, lastIndexOf, and substring js methods... documentation
It is hard to tell the general case from your example, but let me try:
str = str.replace(/\|([^|]+)-Foo\|/, '$1');
Is this helpful?
theString = theString.replace(/\|(.+)-.+\|/, "$1");
There are several answers given. This one replaces
"anything*& 45|anything8 \$-().?anything| 90fanything"
with
"anything*& 45anything8 \$ 90fanything"
The best answer depends on what could possibly be in between the pipes.
I need to capture the price out of the following string:
Price: 30.
I need the 30 here, so I figured I'd use the following regex:
([0-9]+)$
This works in Rubular, but it returns null when I try it in my javascript.
console.log(values[1]);
// Price: 100
var price = values[1].match('/([0-9]+)$/g');
// null
Any ideas? Thanks in advance
Try this:
var price = values[1].match(/([0-9]+)$/g);
JavaScript supports RegExp literals, you don't need quotes and delimiters.
.match(/\d+$/) should behave the same, by the way.
See also: MDN - Creating a Regular Expression
Keep in mind there are simpler ways of getting this data. For example:
var tokens = values[1].split(': ');
var price = tokens[1];
You can also split by a single space, and probably want to add some validation.
Why don't you use this?
var matches = a.match(/\d+/);
then you can consume the first element (or last)
my suggestion is to avoid using $ in the end because there might be a space in the end.
This also works:
var price = values[1].match('([0-9]+)$');
It appears that you escaped the open-perens and therefore the regex is looking for "(90".
You don't need to put quotes around the regular expression in JavaScript.