Slice from sections from URL - javascript

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

Related

Specific pattern matching in Regex in 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);

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

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);

Search through string with Javascript

Say I have a string like this:
jJKld-xxx-JKl122
Using javascript, how can I get on what's in-between the - characters? In others words, all I need to do is put whatever is xxx into a variable.
Thanks
If the string is always in that format, this will work:
var foo = 'jJKld-xxx-JKl122';
var bar = foo.split('-')[1]; // = xxx
just try it with this simple regex
var str = 'jJKld-xxx-JKl122';
var xxx = str.replace( /^[^\-]*-|-[^\-]*$/g, '' );
You can simply use the following regex to get the result
var myString = "jJKld-xxx-JKl122";
var myRegexp = /(?:^|\s*)-(.*?)-(?:^|\s*)/g;
var match = myRegexp.exec(myString);
alert(match[1]);
See the demo here

Javascript string separated by a comma

I'm trying to get everything before/after a comma from a string
var test = 'hello,world';
Result:
var one = 'hello';
var two = 'world';
What would be a good way to this?
Thanks
.split
Extra text because I need to write 15 characters for this submission to be approved.
-- edit
okay, more explicitly:
var k = "a,b".split(",");
alert(k[0]);
alert(k[1]);
var test = 'hello,world',
words = test.split(',');
var one = words[0]; // hello
var two = words[1]; // world

Categories

Resources