Javascript string after an expression - javascript

The expression str.substring(0, str.indexOf("begin:")).trim() gets me the string before begin: but if I want the string that comes after begin:, what do I do?

Or use the same substring function but use the length as the first parameter (factoring in the length of "begin:") and nothing for the second:
str.substring(str.indexOf("begin:")+6).trim()
As the docs for substring state: "If indexEnd is omitted, substring() extracts characters to the end of the string."

just split the string at begin: and get the next portion:
var strPortion=str.split("begin:");
var desiredString=strPortion[1].trim();
so if the string is: "Now we begin: it is better to try splitting the string";
the above code will give "it is better to try splitting the string";

Not completely sure, but try:
str.substring(str.indexOf("begin:"),str.length).trim()
I'm not sure if you want 'begin' included or discarded.

var needle = "begin:";
var haystack = "begin: This is a story all about how my life got flipped turned upside down";
var phrase = str.substring(str.indexOf(needle) + needle.length).trim();
That will give you what you are looking for. I only am posting the answer due to others comments of the ambiguity and modulation of the code. So yeah.
Check it out and change the needle if you'd like. Code example shows how to get before the needle as well. https://jsfiddle.net/jL6zxcu3/1/

var needle = "begin:"
str.substring(str.indexOf(needle)+ needle.length, str.length).trim()
Or
var needle = "begin:"
str.substring(str.indexOf(needle)+ needle.length).trim()
The second Paramter is not needed if you want search to the end of string

Related

pretty complex Regex

I did a lot of research, but apparently my Regex skills are not enough to solve this, so I come to humbly ask for advice.
I have a JS var that gets strings similar to this:
"value=8kadctgwqqe0&value=8kaczvfgoyrs&value=8kwkgz2ysm1i"
it doesn't have a fixed lenght. it may return 1 or 20 values, there's no way to know.
As you can see, it returns a big sequence of values that are always between "value=" and "&", except for the last one, that has no "&" in the end.
I need to parse that, and get this in the end:
8kadctgwqqe0
8kaczvfgoyrs
8kwkgz2ysm1i
I don't even know where to start...
Thanks a lot!
personally I would avoid regex for this.
if your string is always in the value=SOMETHING&value=SOMETHINGELSE format use this
string.split("value=").join("").split("&")
according to How to replace all occurrences of a string in JavaScript? its actually quicker to use this over regex also
var string = "value=8kadctgwqqe0&value=8kaczvfgoyrs&value=8kwkgz2ysm1i"
var yourArray = string.split("value=").join("").split("&")
["8kadctgwqqe0", "8kaczvfgoyrs", "8kwkgz2ysm1i"]
You may need to add some tests to ensure the correct format of string if you are not sure about it.
The following RegExp/.filter() should do it:
'value=8kadctgwqqe0&value=8kaczvfgoyrs&value=8kwkgz2ysm1i'.match(/([^=&]+)/g).filter(function(a){return a!='value'});
The .match() will grab the separate query values (and the key names). In order to deal with this, we use .filter() to remove the value results. This will leave it with the correct results.
Sometimes it's better to use regular JavaScript string manipulation (even though this looks like the worst answer)
.filter() is awesome, more info on it here
You can use the following regex:
/(?:^|&)value=([^&]*)/g
regex101 demo
The matches are then stored in the first capture group.
You can now access the capture groups using this method:
var myRegexp = /(?:^|&)value=([^&]*)/g;
var myString = "value=8kadctgwqqe0&value=8kaczvfgoyrs&value=8kwkgz2ysm1i";
match = myRegexp.exec(myString);
while (match != null) {
console.log(match[1]);
match = myRegexp.exec(myString);
}
If you are interested in the keys as well, you can use:
/(?:^|&)([^=&]*)=([^&]*)/g
In that case for each iteration, the key can be found in the first match, and the value in the second one:
var myRegexp = /(?:^|&)([^&=]*)=([^&]*)/g;
var myString = "value=8kadctgwqqe0&value=8kaczvfgoyrs&value=8kwkgz2ysm1i";
match = myRegexp.exec(myString);
while (match != null) {
console.log(match[1]); //key
console.log(match[2]); //value
match = myRegexp.exec(myString);
}
This works as well:
str.match(/value=([^&]*)/g).join("").split('value=').splice(1)

How do I get a list of strings ending in a newline or ending in the end of the string in javascript regex?

I'm pretty frustrated with regex right now. Given:
var text = "This is a sentence.\nThis is another sentence\n\nThis is the last sentence!"
I want regex to return to me:
{"This is a sentence.\n", "This is another sentence\n\n", "This is the last sentence!"}
I think i should use
var matches = text.match(/.+[\n+\Z]/)
but \Z doesn't seem to work. Does javascript have an end of string matcher?
You can use the following regex.
var matches = text.match(/.+\n*/g);
Working Demo
Or you could match a newline sequence "one or more" times or the end of the string.
var matches = text.match(/.+(?:\n+|$)/g);
Try this one: /(.+\n*)/g
See it here: http://regex101.com/r/wK8oX3/1
If you wanted an array and didn't want to keep the "\n" around you could do...
var strings = text.split("\n");
which would yield
["This is a sentence.", "This is another sentence", "", "This is the last sentence!"]
if you wanted to get rid of that empty string chain a filter onto the split...
var strings = text.split("\n").filter(function(s){ return s !== ""; });
Maybe not what you want tho, also not as efficient as the regex options already proposed.
Edit: as torazaburo pointed out using Boolean as the filter function is cleaner than a callback.
var strings = text.split("\n").filter(Boolean);
Edit Again: I keep getting one upped, using the /\n+/ expression is even cooler.
var strings = text.split(/\n+/);
To get an array of sentences:
var matches = text.match(/.+?(?:(?:\\n)+|$)/g);
You can try this,
text.match(/.+/g)

javascript spilt to get part of the word

I tried use javascript spilt to get part of the word : new from What#a_new%20day
I tried code like this:
<script>
var word="What#a_new%20day";
var newword = word.split("%20", 1).split("_", 2);
alert(newword);
</script>
But caused:
Uncaught TypeError: Object What#a_new has no method 'split'
Maybe there have more wiser way to get the word which I need. So can anyone help me? Thanks.
split returns an array, so the second split is trying to operate on the array returned by the first, rather than a string, which causes a TypeError. You'll also want to add the correct index after the second call to split, or newword will also be an array, not the String you're expecting. Change it to:
var newword = word.split("%20", 1)[0].split("_", 2)[1];
This splits word, then splits the string at index 0 of the resulting array, and assigns the value of the string at index 1 of the new array to newword.
Regex to the rescue
var word="What#a_new%20day";
var newword = word.match(/_(.+)%/)[1];
alert(newword);
this returns the first ([1]) captured group ((...)) in the regex (_(.+)%) which is _ followed by any character (.) one or more times (+) followed by %.
the result of a split is an array, not a string. so what you need to do is
<script>
var word="What#a_new%20day";
var newword = word.split("%20", 1)[0].split("_", 2);
alert(newword);
</script>
notice the [0]
split returns an array:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
word.split("%20", 1);
gives an array so you cannot do :
(result from above).split("_", 2);
If split is what your after, go for it, but performance wise, it would be better to do something like this:
var word="What#a_new%20day";
var newword = word.substr(word.indexOf('new'),3)
alert(newword);
Live example: http://jsfiddle.net/qJ8wM/
Split searches for all instances of %20 in the text, whereas indexOf finds the first instance, and substr is fairly cheap performance wise as well.
JsPerf stats on split vs substring (a general case): http://jsperf.com/split-vs-substring

Splitting string in javascript

How can I split the following string?
var str = "test":"abc","test1":"hello,hi","test2":"hello,hi,there";
If I use str.split(",") then I won't be able to get strings which contain commas.
Whats the best way to split the above string?
I assume it's actually:
var str = '"test":"abc","test1":"hello,hi","test2":"hello,hi,there"';
because otherwise it wouldn't even be valid JavaScript.
If I had a string like this I would parse it as an incomplete JSON which it seems to be:
var obj = JSON.parse('{'+str+'}');
and then use is as a plain object:
alert(obj.test1); // says: hello,hi
See DEMO
Update 1: Looking at other answers I wonder whether it's only me who sees it as invalid JavaScript?
Update 2: Also, is it only me who sees it as a JSON without curly braces?
Though not clear with your input. Here is what I can suggest.
str.split('","');
and then append the double quotes to each string
str.split('","'); Difficult to say given the formatting
if Zed is right though you can do this (assuming the opening and closing {)
str = eval(str);
var test = str.test; // Returns abc
var test1 = str.test1; // returns hello,hi
//etc
That's a general problem in all languages: if the items you need contain the delimiter, it gets complicated.
The simplest way would be to make sure the delimiter is unique. If you can't do that, you will probably have to iterate over the quoted Strings manually, something like this:
var arr = [];
var result = text.match(/"([^"]*"/g);
for (i in result) {
arr.push(i);
}
Iterate once over the string and replace commas(,) following a (") and followed by a (") with a (%) or something not likely to find in your little strings. Then split by (%) or whatever you chose.

Find and get only number in string

Please help me solve this strange situation:
Here is code:
The link is so - www.blablabla.ru#3
The regex is so:
var id = window.location.href.replace(/\D/, '' );
alert(id);
The regular expression is correct - it must show only numbers ... but it's not showing numbers :-(
Can you please advice me and provide some informations on how to get only numbers in the string ?
Thanks
You're replacing only the first non-digit character with empty string. Try using:
var id = window.location.href.replace(/\D+/g, '' ); alert(id);
(Notice the "global" flag at the end of regex).
Consider using location.hash - this holds just the hashtag on the end of the url: "#42".
You can write:
var id = location.hash.substring(1);
Edit: See Kobi's answer. If you really are using the hash part of things, just use location.hash! (To self: Doh!)
But I'll leave the below in case you're doing something more complex than your example suggests.
Original answer:
As the others have said, you've left out the global flag in your replacement. But I'm worried about the expression, it's really fragile. Consider: www.37signals.com#42: Your resulting numeric string will be 3742, which probably isn't what you want. Other examples: www.blablabla.ru/user/4#3 (43), www2.blablabla.ru#3 (23), ...
How 'bout:
id = window.location.href.match(/\#(\d+)/)[1];
...which gets you the contiguous set of digits immediately following the hash mark (or undefined if there aren't any).
Use the flag /\D/g, globally replace all the instances
var id = window.location.href.replace(/\D/g, '' );
alert(id);
And /\D+/ gets better performance than /\D/g, according to Justin Johnson, which I think because of \D+ can match and replace it in one shot.

Categories

Resources