Get all characters except hyphen and brackets from string using javascript regex - javascript

I have a string like this:
var myString = "MyString-[ADDAAD]-isGreat";
I want to extract this string into 3 parts:
var stringOne = "MyString-";
var stringTwo = "ADDAAD";
var stringThree = "-isGreat";
I know how to get the string between the two square brackets:
var matches = patternString.match(/\[(.*?)\]/);
now matches[1] contains ADDAAD
But how can I get the other two parts?

Select every character except -, [ and ] using bottom regex.
var myString = "MyString-[ADDAAD]-isGreat";
var parts = myString.match(/[^-\[\]]+/g);
console.log(parts);
So if you want to store values in custom variable, use bottom code
var stringOne = parts[0];
var stringTwo = parts[1];
var stringThree = parts[2];

You may split the string with your regex. Note that all the capturing group contents will be also part of the resulting array. To avoid empty items, you may add .filter(Boolean) after split().
See a JS demo below:
var myString = "MyString-[ADDAAD]-isGreat";
console.log(myString.split(/\[(.*?)]/).filter(Boolean));
console.log("s1-[s2]".split(/\[(.*?)]/).filter(Boolean));
Note you do not have to escape a ] used outside character classes, it is always parsed as a literal closing bracket if there is no corresponding [ before it.

Related

JS split, keep delimiter minus its first character

Original, string: "FOO,blue,FOO,yellow,red,FOO,purple,brown,blue,FOOred,orange,FOO,blue,yellow"
I'd like to convert this mixed string to an array, splitting specifically at each ,FOO, and keep FOO.
Code:
var str = "blue,FOO,yellow,red,FOO,purple,brown,blue,FOOred,orange,FOO,blue,yellow"
var regex = /(?=,FOO)/g
console.log(str.split(regex))
Codepen
Desired result:
[
'FOO,blue',
'FOO,yellow,red',
'FOO,purple,brown,blue',
'FOOred,orange',
'FOO,blue,yellow',
]
Current result:
[
'FOO,blue',
',FOO,yellow,red',
',FOO,purple,brown,blue',
',FOOred,orange',
',FOO,blue,yellow',
]
As you see, each FOO instance included the preceding comma; how can I exclude the comma in the same regex operation?
var str = "FOO,blue,FOO,yellow,red,FOO,purple,brown,blue,FOOred,orange,FOO,blue,yellow"
var regex = /(?=,FOO)/g
console.log(str.split(regex))
You're only looking ahead for the comma at the moment - you need to include it in the match (outside of the lookahead) for it to be split upon and not included in the result.
var str = "FOO,blue,FOO,yellow,red,FOO,purple,brown,blue,FOOred,orange,FOO,blue,yellow"
var regex = /,(?=FOO)/g
console.log(str.split(regex))

Need to extract values from string in Javascript between words and characters

I will be receiving the following string format from an AJAX call:
[link=https://www.w3schools.com text=here]
I need to extract the values after "link=" and the value after "text=" so, my ideal output would assign "https://www.w3schools.com" to a variable and then "here" to a variable as shown in the code below. The values for "link=" and "text=" will change.
I've tried playing around with regex matching and using .split in Javascript, but I can't get the intended values just right.
var str = "[link=https://www.w3schools.com text=here]";
var link = str.match(/link=(.*)/)[1]; //gets the link but includes rest of string
var linkText = str.match(/text=(.*)/)[1]; //gets "here" plus the closing bracket
add "\s" and "]" in your pattern, Try this
var str = "[link=https://www.w3schools.com text=here]";
var link = str.match(/link=(.*)\s/)[1]; //gets the link but includes rest of string
var linkText = str.match(/text=(.*)]/)[1];
console.log(link);
console.log(linkText);
You may use
var str = "[link=https://www.w3schools.com text=here]";
var m, res=[], rx=/(?:^|[\s[])(link|text)=([^\][\s]*)/g;
while (m = rx.exec(str)) {
console.log(m[1], "=", m[2]);
}
The regex is
/(?:^|[\s[])(link|text)=([^\][\s]*)/
See the regex demo.
Details
(?:^|[\s[]) - start of string or a whitespace or [
(link|text) - Group 1: link or text words
= - a = symbol
([^\][\s]*) - Group 2: any 0+ chars other than [, ] and whitespace.

JavaScript get first name and last name from string as array

I have a string that has the following format: <strong>FirstName LastName</strong>
How can I change this into an array with the first element firstName and second lastName?
I did this, but no luck, it won't produce the right result:
var data = [myString.split('<strong>')[1], myString.split('<strong>')[2]]
How can I produce ["firstName", "lastName"] for any string with that format?
In order to parse HTML, use the best HTML parser out there, the DOM itself!
// create a random element, it doesn't have to be 'strong' (e.g., it could be 'div')
var parser = document.createElement('strong');
// set the innerHTML to your string
parser.innerHTML = "<strong>FirstName LastName</strong>";
// get the text inside the element ("FirstName LastName")
var fullName = parser.textContent;
// split it into an array, separated by the space in between FirstName and LastName
var data = fullName.split(" ");
// voila!
console.log(data);
EDIT
As #RobG pointed out, you could also explicitly use a DOM parser rather than that of an element:
var parser = new DOMParser();
var doc = parser.parseFromString("<strong>FirstName LastName</strong>", "text/html");
console.log(doc.body.textContent.split(" "));
However, both methods work perfectly fine; it all comes down to preference.
Just match everything between <strong> and </strong>.
var matches = "<strong>FirstName LastName</strong>".match(/<strong>(.*)<\/strong>/);
console.log(matches[1].split(' '));
The preferred approach would be to use DOM methods; create an element and get the .textContent then match one or more word characters or split space character.
let str = '<strong>FirstName LastName</strong>';
let [,first, last] = str.split(/<[/\w\s-]+>|\s/g);
console.log(first, last);
/<[/\w\s-]+>|\s/g
Splits < followed by one or more word, space or dash characters characters followed by > character or space to match space between words in the string.
Comma operator , within destructuring assignment is used to omit that index from the result of .split() ["", "FirstName", "LastName", ""].
this is my approach of doing your problem. Hope it helps!
var str = "<strong>FirstName LastName</strong>";
var result = str.slice(0, -9).substr(8).split(" ");
Edit: it will only work for this specific example.
Another way to do this in case you had something other than an html
var string = "<strong>FirstName LastName</strong>";
string = string.slice(0, -9); // remove last 9 chars
string = string.substr(8); // remove first 8 chars
string = string.split(" "); // split into an array at space
console.log(string);

Extract strings between occurences of a specific character

I'm attempting to extract strings between occurences of a specific character in a larger string.
For example:
The initial string is:
var str = "http://www.google.com?hello?kitty?test";
I want to be able to store all of the substrings between the question marks as their own variables, such as "hello", "kitty" and "test".
How would I target substrings between different indexes of a specific character using either JavaScript or Regular Expressions?
You could split on ? and use slice passing 1 as the parameter value.
That would give you an array with your values. If you want to create separate variables you could for example get the value by its index var1 = parts[0]
var str = "http://www.google.com?hello?kitty?test";
var parts = str.split('?').slice(1);
console.log(parts);
var var1 = parts[0],
var2 = parts[1],
var3 = parts[2];
console.log(var1);
console.log(var2);
console.log(var3);
Quick note: that URL would be invalid. A question mark ? denotes the beginning of a query string and key/value pairs are generally provided in the form key=value and delimited with an ampersand &.
That being said, if this isn't a problem then why not split on the question mark to obtain an array of values?
var split_values = str.split('?');
//result: [ 'http://www.google.com', 'hello', 'kitty', 'test' ]
Then you could simply grab the individual values from the array, skipping the first element.
I believe this will do it:
var components = "http://www.google.com?hello?kitty?test".split("?");
components.slice(1-components.length) // Returns: [ "hello", "kitty", "test" ]
using Regular Expressions
var reg = /\?([^\?]+)/g;
var s = "http://www.google.com?hello?kitty?test";
var results = null;
while( results = reg.exec(s) ){
console.log(results[1]);
}
The general case is to use RegExp:
var regex1 = new RegExp(/\?.*?(?=\?|$)/,'g'); regex1.lastIndex=0;
str.match(regex1)
Note that this will also get you the leading ? in each clause (no look-behind regexp in Javascript).
Alternatively you can use the sticky flag and run it in a loop:
var regex1 = new RegExp(/.*?\?(.*?)(?=\?|$)/,'y'); regex1.lastIndex=0;
while(str.match(regex1)) {...}
You can take the substring starting from the first question mark, then split by question mark
const str = "http://www.google.com?hello?kitty?test";
const matches = str.substring(str.indexOf('?') + 1).split(/\?/g);
console.log(matches);

How can I remove all characters up to and including the 3rd slash in a string?

I'm having trouble with removing all characters up to and including the 3 third slash in JavaScript. This is my string:
http://blablab/test
The result should be:
test
Does anybody know the correct solution?
To get the last item in a path, you can split the string on / and then pop():
var url = "http://blablab/test";
alert(url.split("/").pop());
//-> "test"
To specify an individual part of a path, split on / and use bracket notation to access the item:
var url = "http://blablab/test/page.php";
alert(url.split("/")[3]);
//-> "test"
Or, if you want everything after the third slash, split(), slice() and join():
var url = "http://blablab/test/page.php";
alert(url.split("/").slice(3).join("/"));
//-> "test/page.php"
var string = 'http://blablab/test'
string = string.replace(/[\s\S]*\//,'').replace(/[\s\S]*\//,'').replace(/[\s\S]*\//,'')
alert(string)
This is a regular expression. I will explain below
The regex is /[\s\S]*\//
/ is the start of the regex
Where [\s\S] means whitespace or non whitespace (anything), not to be confused with . which does not match line breaks (. is the same as [^\r\n]).
* means that we match anywhere from zero to unlimited number of [\s\S]
\/ Means match a slash character
The last / is the end of the regex
var str = "http://blablab/test";
var index = 0;
for(var i = 0; i < 3; i++){
index = str.indexOf("/",index)+1;
}
str = str.substr(index);
To make it a one liner you could make the following:
str = str.substr(str.indexOf("/",str.indexOf("/",str.indexOf("/")+1)+1)+1);
You can use split to split the string in parts and use slice to return all parts after the third slice.
var str = "http://blablab/test",
arr = str.split("/");
arr = arr.slice(3);
console.log(arr.join("/")); // "test"
// A longer string:
var str = "http://blablab/test/test"; // "test/test";
You could use a regular expression like this one:
'http://blablab/test'.match(/^(?:[^/]*\/){3}(.*)$/);
// -> ['http://blablab/test', 'test]
A string’s match method gives you either an array (of the whole match, in this case the whole input, and of any capture groups (and we want the first capture group)), or null. So, for general use you need to pull out the 1th element of the array, or null if a match wasn’t found:
var input = 'http://blablab/test',
re = /^(?:[^/]*\/){3}(.*)$/,
match = input.match(re),
result = match && match[1]; // With this input, result contains "test"
let str = "http://blablab/test";
let data = new URL(str).pathname.split("/").pop();
console.log(data);

Categories

Resources