JS how to get the substring between two identical string character - javascript

I know to get a substring between 2 characters we can do something like myString.substring(myString.lastIndexOf("targetChar") + 1, myString.lastIndexOf("targetChar"));
But how would I get a substring if the two targetChar are the same. For example, if I have something like const myString = "/theResultSubstring/somethingElse", how would I extract theResultSubstring in this case?

Do indexOf and lastIndexOf if there are only two characters in your string:
const myString = "/theResultSubstring/somethingElse";
const subString = myString.substring(myString.indexOf("/") + 1, myString.lastIndexOf("/"));
console.log(subString);
Or split it:
const myString = "/theResultSubstring/somethingElse";
const subString = myString.split("/")[1];
console.log(subString);

You could use String#match instead with following regex and positive & negative lookaheads.
const myString = "/theResultSubstring/somethingElse";
const res = myString.match(/(?!\/)\w+(?=\/)/)[0];
console.log(res);

Related

Getting the content between two characters

So I have this (example) string: 1234VAR239582358X
And I want to get what's in between VAR and X. I can easily replace it using .replace(/VAR.*X/, "replacement");
But, how would I get the /VAR.*X/as a variable?
I think what you are looking for might be
string.match(/VAR(.*)X/)[1]
The brackets around the .* mark a group. Those groups are returned inside the Array that match creates :)
If you want to only replace what's in between "VAR" and "X" it would be
string.replace(/VAR(.*)X/, "VAR" + "replacement" + "X");
Or more generic:
string.replace(/(VAR).*(X)/, "$1replacement$2");
You can try use the RegExp class, new RegExp(`${VAR}.*X`)
You can store it as variable like this,
const pattern = "VAR.*X";
const reg = new RegExp(pattern);
Then use,
.replace(reg, "replacement");
If you
want to get what's in between VAR and X
then using .* would do the job for the given example string.
But note that is will match until the end of the string, and then backtrack to the first occurrence of X it can match, being the last occurrence of the X char in the string and possible match too much.
If you want to match only the digits, you can match 1+ digits in a capture group using VAR(\d+)X
const regex = /VAR(\d+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
Or you can match until the first occurrence of an X char using a negated character class VAR([^\r\nX]+)X
const regex = /VAR([^\r\nX]+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}

Regex match for string between / and .jsp

If I do regex match for
str = "/mypage/account/info.jsp"
str.match('\/.*\.jsp')
I get entire string but I want to grab only "info"
How can I accomplish using only regex?
First, you can get the text after the last /
/[^/]*$/
and then get the desired result using split
const str = "/mypage/account/info.jsp";
const match = str.match(/[^/]*$/);
const result = match && match[0].split(".")[0];
console.log(result);
only regex
const str = "/mypage/account/info.jsp";
const match = str.match(/[^/]+(?=\.jsp$)/);
console.log(match[0]);

Remove part of the string before the FIRST dot with js

I have the next problem. I need to remove a part of the string before the first dot in it. I've tried to use split function:
var str = "P001.M003.PO888393";
str = str.split(".").pop();
But the result of str is "PO888393".
I need to remove only the part before the first dot. I want next result: "M003.PO888393".
Someone knows how can I do this? Thanks!
One solution that I can come up with is finding the index of the first period and then extracting the rest of the string from that index+1 using the substring method.
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.')+1);
console.log(str)
You can use split and splice function to remove the first entry and use join function to merge the other two strings again as follows:
str = str.split('.').splice(1).join('.');
Result is
M003.PO888393
var str = "P001.M003.PO888393";
str = str.split('.').splice(1).join('.');
console.log(str);
You could use a regular expression with .replace() to match everything from the start of your string up until the first dot ., and replace that with an empty string.
var str = "P001.M003.PO888393";
var res = str.replace(/^[^\.]*\./, '');
console.log(res);
Regex explanation:
^ Match the beginning of the string
[^\.]* match zero or more (*) characters that are not a . character.
\. match a . character
Using these combined matches the first characters in the string include the first ., and replaces it with an empty string ''.
calling replace on the string with regex /^\w+\./g will do it:
let re = /^\w+\./g
let result = "P001.M003.PO888393".replace(re,'')
console.log(result)
where:
\w is word character
+ means one or more times
\. literally .
many way to achieve that:
by using slice function:
let str = "P001.M003.PO888393";
str = str.slice(str.indexOf('.') + 1);
by using substring function
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.') + 1);
by using substr function
let str = "P001.M003.PO888393";
str = str.substr(str.indexOf('.') + 1);
and ...

How do I split a string with multiple separators in javascript without using regexp?

I have this string
let str = "name1,name2/name3"
and I want to split on "," and "/", is there is a way to split it without using regexp?
this is the desire output
name1
name2
name3
Little bit of a circus but gets it done:
let str = "name1,name2/name3";
str.split("/").join(",").split(",");
Convert all the characters you want to split by to one character and do a split on top of that.
You can split first by ,, then convert to array again and split again by /
str.split(",").join("/").split("/")
Without regexp you can use this trick
str.split('/').join(',').split(',')
Use the .split() method:
const names = "name1,name2/name3".split(/[,\/]/);
You still have to use a regex literal as the token to split on, but not regex methods specifically.
Just get imaginative with String.spit().
let str = "name1,name2/name3";
let str1 = str.split(",");
let str2 = str1[1].split("/");
let result = [str1[0],str2[0],str2[1]];
console.log(result);
If you don't want to use regex you can use this function:
function split (str, seps) {
sep1 = seps.pop();
seps.forEach(sep => {
str = str.replace(sep, sep1);
})
return str.split(sep1);
}
usage:
const separators = [',', ';', '.', '|', ' '];
const myString = 'abc,def;ghi jkl';
console.log(split(myString, separators));
You can use regexp:
"name1,name2/name3".split(/,|;| |\//);
this will split by ,, ;, or /
or
"name1,name2/name3".split(/\W/)
this will split by any non alphanumeric char

Regex giving incorrect results

Working in Javascript attempting to use a regular expression to capture data in a string.
My string appears as this starting with the left bracket
['ABC']['ABC.5']['ABC.5.1']
My goal is to get each piece of the regular expression as a chunk or in array.
I have reviewed and see that the match function might be a good choice.
var myString = "['ABC']['ABC.5']['ABC.5.1']";
myString.match(/\[/g]);
The output I see is only the [ for each element.
I would like the array to be like this for example
myString[0] = ['ABC']
myString[1] = ['ABC.5']
myString[2] = ['ABC.5.1']
What is the correct regular expression and or function to get the above-desired output?
If you just want to separate them, you can use a simple expression or better than that you can split them:
\[\'(.+?)'\]
const regex = /\[\'(.+?)'\]/gm;
const str = `['ABC']['ABC.5']['ABC.5.1']`;
const subst = `['$1']\n`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
DEMO
You can use this regex with split:
\[[^\]]+
Details
\[ - Matches [
[^\]]+ - Matches anything except ] one or more time
\] - Matches ]
let str = `['ABC']['ABC.5']['ABC.5.1']`
let op = str.split(/(\[[^\]]+\])/).filter(Boolean)
console.log(op)

Categories