Specific pattern matching in Regex in Javascript - javascript

I want to use regex to match the string of the following format :
(#sometext#)
In the sense ,whatever is there between (# and #) only should be matched.
So, the text:
var s = "hello(%npm%)hi";
var res = s.split(/(\([^()]*\))/);
alert(res[0]);
o/p: hello(%npm%)hi
And
var s = "hello(#npm#)hi";
var res = s.split(/(\([^()]*\))/);
alert(res[0]);
o/p: hello
alert(res[1]);
o/p : (#npm#);
But the thing is , the regex /(\([^()]*\))/ is matching everything between () rather than extracting the string including (# .. #)
like:
hello
(#npm#)
hi

By going in your way of fetching content, try this:
var s = "hello(%npm%)hi";
var res = s.split(/\(%(.*?)%\)/);
alert(res[1]);
//o/p: hello(%npm%)hi
var s = "hello(#npm#)hi";
var res = s.split(/(\(#.*?#\))/);
console.log(res);
//hello, (#npm#), hi
From your comment, updated the second portion, you get your segments in res array:
[
"hello",
"(#npm#)",
"hi"
]

The following pattern is going to give the required output:
var s = "hello(#&yu()#$#8#)hi";
var res = s.split(/(\(#.*#\))/);
console.log(res);
"." matches everything between (# and #)

It depends if you have multiple matches per string.
// like this if there is only 1 match per text
var text = "some text #goes#";
var matches = text.match(/#([^#]+)#/);
console.log(matches[1]);
// like this if there is multiple matches per text
var text2 = "some text #goes# and #here# more";
var matches = text2.match(/#[^#]+#/g).map(function (e){
// strip the extra #'s
return e.match(/#([^#]+)#/)[1];
});
console.log(matches);

Related

Slice from sections from URL

Given these URLs:
/content/etc/en/hotels/couver/offers/residents.html
/content/etc/en/offers/purchase.html
I want to remove (slice) from the URL and get only /offers/residents and /offers/purchase
I wrote this code to do it but I'm getting different results than I require. Please let me know which syntax will work as expected.
var test1 = '/content/etc/en/hotels/couver/offers/residents.html'
test1 = test1.slice(0,5);
var test2 = '/content/etc/en/offers/purchase.html'
test2 = test2.slice(0,5);
One way to achieve this would be to split the strings by / and then only use the last two sections of the path to rebuild a string:
['/content/etc/en/hotels/couver/offers/residents.html', '/content/etc/en/offers/purchase.html'].forEach(function(url) {
var locs = url.replace(/\.\w+$/, '').split('/');
var output = locs.slice(-2).join('/');
console.log(output);
});
Alternatively you could use a regular expression to only retrieve the parts you require:
['/content/etc/en/hotels/couver/offers/residents.html', '/content/etc/en/offers/purchase.html'].forEach(function(url) {
var locs = url.replace(/.+\/(\w+\/\w+)\.\w+$/, '$1');
console.log(locs);
});
You could extract the substring that you want with regex. In the example below the matches[1] will contain the wanted substring.
var str = '/content/etc/en/hotels/couver/offers/residents.html';
var matches = str.match(/([\w]+\/[\w]+)\.html/);
var parsed = matches[1];
this is what you meant for?
to change the slice numbers?
var test1 = '/content/etc/en/hotels/couver/offers/residents.html'
test1 = test1.slice(29,46);
var test2 = '/content/etc/en/offers/purchase.html'
test2 = test2.slice(15,31);
Use regex, to remove everything before and after string, that starts from /offers and ends with .html
const str1 = '/content/etc/en/hotels/couver/offers/residents.html';
const str2 = '/content/etc/en/offers/purchase.html';
const regex = /^(.*)(\/offers\/.*)(.html)$/g;
console.log(str1.replace(regex, '$2')); // /offers/residents
console.log(str2.replace(regex, '$2')); // /offers/purchase
https://regex101.com/r/hRwLHi/1

How to extract query string parameters from URL in JavaScript

I have a URL
https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama
I want to get search_terms (Generator+Repair) and geo_location_terms (Adamsville%2C+Alabama)
How I can do this?
The easiest and most idiomatic way to do this in JavaScript is using the URL class:
const url = new URL('https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama')
console.log(url.searchParams.get('search_terms'));
console.log(url.searchParams.get('geo_location_terms'));
MDN reference here.
You can use the following Javascript code to store the GET parameters into an object:
<script>
var URL = "https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama";
var result = {};
URL.substring(URL.indexOf("?") + 1).split('&').forEach(function(x){
var arr = x.split('=');
arr[1] && (result[arr[0]] = arr[1]);
});
console.log(result.search_terms);
//OUTPUT: "Generator+Repair"
console.log(result.geo_location_terms);
//OUTPUT: "Adamsville%2C+Alabama"
</script>
You can use the following regex to get the 2 values:
/search_terms=(.*)&geo_location_terms=(.*)/
This is a very basic regex, that starts by matching 'search_terms=' then creates a Group that matches any number of any char up to the '&' sign, then matches 'geo_location_terms=' and finally creates a Group that matches any number of any char.
Your desired output will be in Group 1 and Group 2.
How to use:
var url = 'https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama';
var regex = /search_terms=(.*)&geo_location_terms=(.*)/;
var match = url.match(regex);
var search_terms = match[1];
var geo_location_terms = match[2];

How to split a string by <span> tag in Javascript

I have a data.text string that returns a value like:
<span>Name</span>Message
Is it possible in Javascript to take this value and split in to two so that I can get 'Name' and 'Message' in two different variables?
I tried,
var str = data.text;
var arr[] = str.split("</span>", 2);
var str1 = arr[0];
var theRest = arr[1];
But didn't work
You should use a DOM parser to parse HTML.
var str = "<span>Name</span>Message",
el = document.createElement('div');
el.innerHTML = str;
[].map.call(el.childNodes, function(node) {
return node.textContent;
}); // [ "Name", "Message" ]
There might be many methods but adding on using split.
var str = '<span>Name</span>Message';
var result = str.split(/<\/?span>/); // Split by span tags(opening and closing)
result.shift(); // Remove first empty element
console.log(result);
document.write(result);
The regex here <\/?span> will match the <span> and </span> both as in the regex \/? has made / optional.
You can also use following regex with non-capturing group.
(?:</?span>)(\w+)
var str = '<span>Name</span>Message';
var regex = /(?:<\/?span>)(\w+)/g,
result = [];
while (res = regex.exec(str)) {
result.push(res[1]);
}
console.log(result);
document.write(result);
You can replace the open label with a empty string and then split the string by the close label, something like this:
var values = data.text.replace('<span>', '').split('</span>');
console.log(values[0]); // Name
console.log(values[1]); // Message

How to "place-hold" regex matches in array using javascript

If I have a multiple match regex like:
var matches = string.match(/\s*(match1)?\s*(match2)?(match3)?\s*/i);
and if my string that I am testing is like this:
var string = "match1 match3";
is there a way to output this array values:
matches[1] = "match1";
matches[2] = "";
matches[3] = "match3";
Notice: what I would like is for the regex to match the entire thing but "place-hold" in the array the matches it does not find.
Hope this makes sense. Thanks for the help!
There already is a "placeholder". Unmatched groups pop an array index matching the group number with an undefined value. e.g.
var someString = "match2";
var matches = someString.match(/\s*(match1)?\s*(match2)?(match3)?\s*/i);
matches now has
["match2", undefined, "match2", undefined]
Element 0 is the complete regex match and elements 1-3 are the individual groups
So you can do for example...
// check if group1
if (typeof matches[1] != 'undefined')
When you want to compare the string to the regexes, just do an Array join.Something like,
matches[1] = "match1";
matches[2] = "";
matches[3] = "match3";
var mystring = mathches.join("");
The joining character could be anything. You could also do,
var mystring = mathches.join(" ");
EDIT:
Not sure from the problem description, but i think you want the regex to output an array.Something like
text = "First line\nSecond line";
var regex = /(\S+) line\n?/y;
would give,
var match = regex.exec(text);
print(match[1]); // prints "First"
print(regex.lastIndex); // prints 11
More about it here

Regex remove repeated characters from a string by javascript

I have found a way to remove repeated characters from a string using regular expressions.
function RemoveDuplicates() {
var str = "aaabbbccc";
var filtered = str.replace(/[^\w\s]|(.)\1/gi, "");
alert(filtered);
}
Output: abc
this is working fine.
But if str = "aaabbbccccabbbbcccccc" then output is abcabc.
Is there any way to get only unique characters or remove all duplicates one?
Please let me know if there is any way.
A lookahead like "this, followed by something and this":
var str = "aaabbbccccabbbbcccccc";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "abc"
Note that this preserves the last occurrence of each character:
var str = "aabbccxccbbaa";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "xcba"
Without regexes, preserving order:
var str = "aabbccxccbbaa";
console.log(str.split("").filter(function(x, n, s) {
return s.indexOf(x) == n
}).join("")); // "abcx"
This is an old question, but in ES6 we can use Sets. The code looks like this:
var test = 'aaabbbcccaabbbcccaaaaaaaasa';
var result = Array.from(new Set(test)).join('');
console.log(result);

Categories

Resources