JS Substrings understanding? [duplicate] - javascript

This question already has answers here:
Why are slice and range upper-bound exclusive?
(6 answers)
Closed 9 years ago.
I'm on Codecademy and I am learning JavaScript. I'm on substrings and I get how to do them, but I wander why substrings extracts characters from indexA up to but not including indexB. Why does it include indexA, but only up to indexB?
Please use the best layman's term for this, considering I don't have that much knowledge in this language (I'm only familiar with HTML & CSS).

var longString = "this is a long string";
var substr1 = longString.substring(0, 4); //"this"
var substr2 = longString.substring(4, 8); //" is "
This makes sense because the second substring started from where the first left off, without copying the same letter twice in both substrings. It makes it more useful in loops, for example.
Also, as everyone keeps pointing out, because "it's defined that way..."

That's because it's designed that way. Here's some documentation from MDN.
"Hello World".substring(0,5) //Hello
Simply saying
Get the substring starting with (and including) the character at the first index, and ending (but not including) the character at the second index.

Well, the method is defined in that way. Extracts from indexA up to indexB but not including.

In Javascript there are two different functions to extract a substring. One with length and other with index start and stop.
String.substring( from [, to ] )
String.substr( start [, length ] )
In all cases, the second argument is optional. If it is not provided, the substring will consist of the start index all the way through the end of the string.
Please go through this article to clear up.
http://www.bennadel.com/blog/2159-Using-Slice-Substring-And-Substr-In-Javascript.htm

Related

Am confused about the functions of caret(^) in Regular expresssions. What does it mean here [^'] and what does it mean here [^01] [duplicate]

This question already has answers here:
Negating specific characters in regex
(4 answers)
Reference - What does this regex mean?
(1 answer)
Closed 20 days ago.
I have a regular expression:
/'([^']*)'/
Am finding it hard to understand how it works. The function of the caret here confuses me.
Unlike this regex:
/[^01]/ : i understand the caret here is an inverter which means the search should return true for any input input value that is different from 01.
let quotedText = /'([^']*)'/;
console.log(quotedText.exec("She said 'hello'"));
The console: ["'hello'", "hello"]
I do understand how the regexpression(quotedText) finds hello. What if the statement was longer with more words in quote. Like:
("She said 'hello' and he responded 'Hi', 'do you need my help'").
Would the exec method find all the words or sentences in quotes?.
I am also very confused about the function of caret^ here. Is it inverting?? Or is it showing where the exec methods starts looking from. Whats the difference between [^']* and [^01]. Does the function of caret change based on the method. Does caret(^) you see work differently when used with test method or exec method?. does Caret behave differently when in square brackets?

Add a space after every character in a string JavaScript [duplicate]

This question already has answers here:
How to add spaces between every character in a string?
(4 answers)
Closed 3 years ago.
How can i convert a text like Test to T e s t I know It can probably be done with regex but i don't understand how
I've, Quite new to javascript, in python (Which i quite understand) It can be done with a for loop something like
print(" ".join(a for a in "Test"))
But join works differently in javascript and only works for arrays (lists) if i'm right
I've also tried using replace but it does nothing
console.log("Test".replace(""," "))
console.log("Test".replace(""," "))
"Test".split("").join(" ")
// or
[..."Test"].join(" ")
Thats it. You can't do that with .join directly as that only accepts a string.
JS doesn't support generator expressions, and join is an array method that takes the joiner not a string method that takes an iterable. The closest equivalent to your Python code would be
console.log(Array.from("Test").join(" "))
Using Array.from (converting the iterable string to an array) over .split("") has the advantage that it doesn't break unicode characters that consist of multiple code points apart.

How to use RegEx with a variable for replacing [duplicate]

This question already has answers here:
Javascript Regex: How to put a variable inside a regular expression? [duplicate]
(9 answers)
Closed 4 years ago.
My title might not be worded correctly sorry in advance.
I've looked everywhere and I honestly can't seem to figure it out.
I want to use a variable in a RegEx but the solution that i've found and tried to work off of works but it is not flexible for what I need. I can't seem to figure out how to convert it to a RegEx constructor object which I think is my best bet. Any help will be greatly appreciated.
let str = 'haeandviaecy'
let newString = str.replace(/(\w{3})/g, '$1 ').replace(/(^\s+|\s+$)/, '')
//hae and via ecy
replace(/(^\s+|\s+$)/,'') removes any preceding or trailing space from the string - just giving you a heads up
So what this snippet does is go to every third and put a blank space in it. What I want is to make my code more flexible and be able to put a variable to let me choose the number for when it puts a blank space using a variable.
right now it prints out - "hae and via ecy"
for ex. every 4th would be - haea ndvi aecy
I've read you cant put in variables unless it is a RegEx contructor object. When I've tried to convert it doesn't seem to work.
If gather the question correctly, you can use a template literal as parameter passed to RegExp constructor.

What should the javascript match() regex function return? [duplicate]

This question already has answers here:
Match all consecutive numbers of length n [duplicate]
(3 answers)
Closed 5 years ago.
Take this example:
"12345".match(/(?=(\d{4}))/g);
Pasting that line above into my (Chrome) console is returning ["", ""] for me but I am trying to extract an array of ["1234", "2345"]. This MDN article seems to indicate that I should, indeed, expect an array of matches.
The particular regex on this exact string definitely returns those matches as proven in this question from yesterday.
Can anyone please clarify what the expected behavior should be and any alternative approaches I could take here if I have made an incorrect assumption about this function and/or am misusing it.
You cited the question Match all consecutive numbers of length n. Why not take the code from the accepted answer there (https://stackoverflow.com/a/42443329/4875869)?
What goes wrong with "12345".match(/(?=(\d{4}))/g); is that in ["", ""] the first "" corresponds to the match with $0 (the whole match) = "", $1 (group 1) = "1234", and so for the second "" (the array is like [$0 (match 1), $0 (match 2)] because of g).
If you omit the g ("12345".match(/(?=(\d{4}))/);), you'll get ["", "1234"] ([$0 (the match), $1 (the match)]).
Edit: It seems regular expressions are not the right tool for the job, as explained by trincot above.
In an attempt to redeem myself, here is a fun solution involving arrays and slice. The literal 4 can be substituted for any other number to achieve a similar effect.
console.log(
'12345'.split('').map((_, i, a) => a.slice(i, i + 4).join('')).slice(0, 1 - 4)
)

RegEx: Extract GET variable from URL [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 9 years ago.
RegExp gurus, heed my call!
This is probably super simple, but I've painted myself in a mental corner.
Taking a regular URL, split after the ?, which gives a string like variable=val&interesting=something&notinteresting=somethingelse I want to extract the value of interesting.
The name of the variable I'm interested in can be a substring of another variable.
So the match should be
either beginning of string or "&" character
followed by "interesting="
followed by the string I want to capture
followed by either another "&" or end of string
I tried something along the lines of
[\^&]interesting=(.*)[&$]
but I got nothing...
Update
This is to be run in a Firefox addon on every get request, meaning that jQuery is not available and if possible I would like to avoid the extra string manipulation caused by writing a function.
To me this feels like a generic "extract part of a string with regex" but maybe I'm wrong (RegEx clearly isn't my strong side)
simple solution
var arr = "variable=val&interesting=something&notinteresting=somethingelse".split("&");
for(i in arr) {
var splits = arr[i].split("=");
if(splits[0]=="interesting") alert(splits[1]);
}
also single line match
"variable=val&interesting=something&notinteresting=somethingelse".match(/(?:[&]|^)interesting=((?:[^&]|$)+)/)[1]
function getValue(query)
{
var obj=location.search.slice(1),
array=obj.split('&'),
len=array.length;
for(var k=0;k<len;k++)
{
var elm=array[k].split('=');
if(elm[0]==query)return elm[1];
}
}
This function directly extract the query URL and return the corresponding value if present.
//usage
var get=getValue('interesting');
console.log(get);//something
If you're using the Add-on SDK for Firefox, you can use the url module:
https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/url.html
This is much better than using regex.

Categories