SubString in JavaScript [duplicate] - javascript

This question already has answers here:
How to get the nth occurrence in a string?
(14 answers)
Closed 2 years ago.
For example, I have a string like following
var string = "test1;test2;test3;test4;test5";
I want the following substring from the above string, I don't know the startIndex, the only thing I can tell substring should start after the second semicolon to till the end.
var substring = "test3;test4;test5";
Now I want to have substring like following
var substring2 = "test4;test5"
How to achieve this in JavaScript

You mean this?
const string = "test1;test2;test3;test4;test5";
const arr = string.split(";")
console.log(arr.slice(2).join(";")); // from item #2
console.log(arr.slice(-2).join(";")) // last 2 items
If the string is very long, you may want to use one of these versions
How to get the nth occurrence in a string?
As a function
const string = "test1;test2;test3;test4;test5";
const restOfString = (string,pos) => {
const arr = string.split(";")
return arr.slice(pos).join(";"); // from item #pos
};
console.log(restOfString(string,2))
console.log(restOfString(string,3))

Try to use a combination of string split and join to achieve this.
var s = "test1;test2;test3;test4;test5";
var a = s.split(";")
console.log(a.slice(3).join(";"))

Related

how to find the first number from string in js(javascript)? [duplicate]

This question already has answers here:
Get the first integers in a string with JavaScript
(5 answers)
Closed 6 months ago.
How to find the first number from string in javascript?
var string = "120-250";
var string = "120,250";
var string = "120 | 250";
Here is an example that may help you understand.
Use the search() method to get the index of the first number in the string.
The search method takes a regular expression and returns the index of the first match in the string.
const str = 'one 2 three 4'
const index = str.search(/[0-9]/);
console.log(index); // 4
const firstNum = Number(str[index]);
console.log(firstNum); // 2
Basic regular expression start of string followed by numbers /^\d+/
const getStart = str => str.match(/^\d+/)?.[0];
console.log(getStart("123,456"));
console.log(getStart("123-456"));
console.log(getStart("123|456"));
console.log(getStart("xxx,xxx"));
Or parseInt can be used, but it will drop leading zeros.
const getStart = str => parseInt(str, 10);
console.log(getStart("123,456"));
console.log(getStart("123-456"));
console.log(getStart("123|456"));
console.log(getStart("xxx,xxx"));

How to create a function to split the following string? [duplicate]

This question already has answers here:
What is the shortest function for reading a cookie by name in JavaScript?
(20 answers)
Closed 2 years ago.
I have this string
"G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;
_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5"
And i need some sort of function to split this string given an argument , for example given that my string is text
text.split(";") , will split it into an array separating it by ";"
But i need a function like this
returnText(text , property) that would work like
returnText(text, "_gcl_au") --> returns "someglcau"
You could actually use a regex replacement approach here, for a one-liner option:
function returnText(text, property) {
var term = text.replace(new RegExp("^.*\\b" + property + "=([^;]+)\\b.*$", "gm"), "$1");
return term;
}
var input = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie;_ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(input, "_gcl_au"));
you can use split, just as you tried:
function returnText(text , property){
entries = text.split('; ');
const newEntries = [];
entries.forEach(item => {
let vals = item.split('=');
newEntries[vals[0]] = vals[1]
});
return newEntries[property];
}
const text = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(text,'_gcl_au'));

RegEx for checking multiple matches [duplicate]

This question already has answers here:
How can I match overlapping strings with regex?
(6 answers)
Closed 3 years ago.
I want to match all occurrence in string.
Example:
pc+pc2/pc2+pc2*rr+pd
I want to check how many matched of pc2 value and regular expression is before and after special character exists.
var str = "pc+pc2/pc2+pc2*rr+pd";
var res = str.match(new RegExp("([\\W])pc2([\\W])",'g'));
But I got only +pc2/ and +pc2* and /pc2+ not get in this.
Problem is in first match / is removed. So after that, it is starting to check from pc2+pc2*rr+pd. That's why /pc2+ value does not get in the match.
How do I solve this problem?
You need some sort of recursive regex to achieve what you're trying to get, you can use exec to manipulate lastIndex in case of value in string is p
let regex1 = /\Wpc2\W/g;
let str1 = 'pc+pc2/pc2+pc2*rr+pd';
let array1;
let op = []
while ((array1 = regex1.exec(str1)) !== null) {
op.push(array1[0])
if(str1[regex1.lastIndex] === 'p'){
regex1.lastIndex--;
}
}
console.log(op)

Check whether an array includes a string but ignore rest other letters in that string [duplicate]

This question already has answers here:
Is there a javascript method to find substring in an array of strings?
(5 answers)
How to check if a string contains text from an array of substrings in JavaScript?
(24 answers)
Closed 4 years ago.
I have a variable like,
var url = "/login/user";
And I have an array like,
var x = ["login", "resetpassword", "authenticate"];
Now I need to check, whether that url string is present in an array of string. As we can see that login is present in an array but when i do x.indexOf(url), it always receive false because the field url has rest other letters also. So now how can I ingnore those letters while checking a string in an array and return true?
Use .some over the array instead:
var url = "/login/user";
var x = ["login", "resetpassword", "authenticate"];
if (x.some(str => url.includes(str))) {
console.log('something in X is included in URL');
}
Or, if the substring you're looking for is always between the first two slashes in the url variable, then extract that substring first, and use .includes:
var url = "/login/user";
var x = ["login", "resetpassword", "authenticate"];
var foundStr = url.split('/')[1];
if (x.includes(foundStr)) {
console.log('something in X is included in URL');
}
One way is to split url with / character and than use some
var url = "/login/user";
var x = ["login", "resetpassword", "authenticate"];
let urlSplitted = url.split('/')
let op = urlSplitted.some(e=> x.includes(e))
console.log(op)
You could join the given words with a pipe (as or operator in regex), generate a regular expression and test against the string.
This works as long as you do not have some characters with special meanings.
var url = "/login/user",
x = ["login", "resetpassword", "authenticate"];
console.log(new RegExp(x.join('|')).test(url));

Return only a part of the match [duplicate]

This question already has an answer here:
Get part of the string using regexp [closed]
(1 answer)
Closed 9 years ago.
Here's an example http://jsbin.com/USONirAn/1
var string = "some text username#Jake# some text username#John# some text some text username#Johny# userphoto#1.jpg#";
var type = "username";
var regexp = new RegExp(type + "#(.*?)#");
var matches = string.match(regexp);
Current regexp returns into matches an array with 3 items - [username#Jake#, username#John#, username#Johny#].
How do I make it return only a strings that I used to search for - (.*?)? In this example is should be an array [Jake, John, Johny]. Is it possible to get this only by changing a regexp function?
Update:
I've also tried to use exec function, but it returns both [username#Jake#, Jake] http://jsbin.com/USONirAn/6
Search-and-don't-replace
var matches = []
string.replace(regexp, function () {
matches.push(arguments[1]);
});
http://jsbin.com/USONirAn/4

Categories

Resources