I have a problem and I cannot seem to solve it.
I have some URL's like this:
http://www.example.com/test/filter=show
http://www.example.com/test/filter=show/results=true
I want to remove only \/filter=(\w+)(\/?), so only filter=show but do not include the next forward slash. Also filter is just a variable.
What I have tried:
var url = 'http://www.example.com/test/filter=show/results=true';
var param = 'filter';
var oldParam = '\/('+param+'=(.*?))';
var reg = new RegExp(oldParam, "gi");
var result = url.replace(reg, "/");
This removes only filter= and leave out show.
Any help is greatly appreciated.
try it
var url = 'http://www.example.com/test/filter=show/results=true';
var result = url.replace(/filter=([^&\/]*[/]?)/gi, "");
alert(result);
================= UPDATE ==================
var url = 'http://www.example.com/test/filter=show/results=true';
var params = 'filter';
params = params+'=([^&\/]*[/]?)'
var reg = new RegExp(params, "gi");
var result = url.replace(reg, "");
alert(result);
Try look ahead like
'http://www.example.com/test/filter=show/results=true'.replace(/\/filter=.*?(?=\/)/, '')
Ex:
var url = 'http://www.example.com/test/filter=show/results=true';
var param = 'filter';
var oldParam = '\\/'+param+'=.*?(?=\\/)';
console.log(oldParam)
var reg = new RegExp(oldParam, "gi");
var result = url.replace(reg, "");
console.log(result)
Demo: Fiddle
This should suit your needs:
var url = "http://www.example.com/test/filter=show/results=true";
var param = "filter";
var pattern = "/" + param + "=[^/]+";
var regex = new RegExp(pattern, "gi");
var result = url.replace(regex, "");
document.write(result);
Prints:
http://www.example.com/test/results=true
Explanation:
/filter=[^/]+
Edit live on Debuggex
Related
I want to highlight in a text all the occurrences from a word that I have in my URL.
For the first occurrence everything works fine. But I don't know how to go to the next one.
highlightText: function(urlParams) {
var urlSearch = window.location.search;
var urlParams = new URLSearchParams(urlSearch);
var searchText = urlParams.get('search');
if (window.find(searchText)) {
var el = document.getElementById('collection-content');
text = el.innerHTML;
marked = text.replace(searchText, "<mark>" + searchText + "</mark>");
el.innerHTML = marked;
}
}
I have tried to add a while(window.find(searchText) before the if but it doesn't work, it seems to loop only on the first occurence of my word.
Thanks in advance
If you're not using regex then it'll only replace the first occurrence, you might try this, Also modify the regex as per your needs.
highlightText: function(urlParams) {
var urlSearch = window.location.search;
var urlParams = new URLSearchParams(urlSearch);
var searchText = urlParams.get('search');
if (window.find(searchText)) {
var el = document.getElementById('collection-content');
text = el.innerHTML;
marked = text.replace(
RegExp(`(${searchText})`),
"<mark>" + searchText + " </mark>");
el.innerHTML = marked;
}
}
Note: The match is case sensitive
I have the following function:
function parseEntry(query, html, url) {
// logic draft :(
var re = new RegExp('{{{(.*)}}}');
regex = query.replace(re, "$1");
var newre = new RegExp(regex);
regged = html.replace(newre, "$1");
ret = query.replace(regex, regged);
// parse selectors
var re = new RegExp('{{(.*)}}');
newtext = html.replace(re, "$1");
ret = ret.replace(newtext, $(newtext).clone().html());
// parse %url%
ret = ret.replace("%url%", url);
// ret remaining
return ret;
}
// Called this way:
let output = parseEntry('static value %url% {{.thisclass}} {{{(\d+)}}}', '<h1 class="thisclass">Test</h1><h2 class="thisclass">Test2</h2> 1234 12', "http://perdu.com");
console.log(output)
/**
should return:
static value http://perdu.com TestTest2 123412
{{{triple brackets = regex}}}
{{double brackets = jquery}}
**/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Can you help refactoring parseEntry() function to return expected output?
All help appreciated!
I'm not sure if I undersand, but this is an attempt using different approaches I think are useful in this kind of situations. There are examples of split(), replace() and the createElement hack to parse html.
var query = 'static value %url% {{.thisclass}} {{{(\d+)}}}';
var html = '<h1 class="thisclass">Test</h1><h2 class="thisclass">Test2</h2> 1234 12';
var url = "http://perdu.com";
query = query.split(" ").map(o=>{
return o.replace(/\{\{\{(.*)\}\}\}/g, "$1");
}).map(o=>{
return o.replace(/\{\{(.*)\}\}/g, "$1");
});
var el = document.createElement( 'div' );
el.innerHTML = "<div class='outer'>"+html+"</div>";
var t1 = $("h1").text();
var t2 = $("h2").text();
var out = $(".outer").text();
var newArr = [];
newArr.push(query[0]+" "+query[1]+" "+url+" "+t1+t2+out);
newArr.push("{{{triple brackets = "+query[4]+"}}}");
newArr.push("{{double brackets = "+query[3]+"}}");
console.log(newArr);
newArr.map(o=>{
$("#res").append(o+"<br>");
});
Full example here: http://jsfiddle.net/k8em5twd/6/
So if this question is as simple as "why didn't the backslash show up in my output", then the answer is also very simple. Try escaping the backslash in your input string like so:
let output = parseEntry('static value %url% {{.thisclass}} {{{(\\d+)}}}', '<h1 class="thisclass">Test</h1><h2 class="thisclass">Test2</h2> 1234 12', "http://perdu.com");
The key is that {{{(\d+)}}} becomes {{{(\\d+)}}}. This way the slash is recognized as a character. Otherwise, \d is treated as an escape sequence. Output below.
function parseEntry(query, html, url) {
// logic draft :(
var re = new RegExp('{{{(.*)}}}');
regex = query.replace(re, "$1");
var newre = new RegExp(regex);
regged = html.replace(newre, "$1");
ret = query.replace(regex, regged);
// parse selectors
var re = new RegExp('{{(.*)}}');
newtext = html.replace(re, "$1");
ret = ret.replace(newtext, $(newtext).clone().html());
// parse %url%
ret = ret.replace("%url%", url);
// ret remaining
return ret;
}
// Called this way:
// THIS LINE IS CHANGED:
let output = parseEntry('static value %url% {{.thisclass}} {{{(\\d+)}}}', '<h1 class="thisclass">Test</h1><h2 class="thisclass">Test2</h2> 1234 12', "http://perdu.com");
console.log(output)
/**
should return:
static value http://perdu.com TestTest2 123412
{{{triple brackets = regex}}}
{{double brackets = jquery}}
**/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Ended up doing it myself, for the curious:
function parseEntry(query, url, ht) {
// parse regex expressions (triple brackets)
var re = new RegExp('{{{(.*)}}}', 'g');
q = query.match(re);
for (qq in q) {
var newregex = q[qq].replace("{{{", '').replace("}}}", '');
newregex = new RegExp(newregex, 'g');
newq = ht.match(newregex).join("");
query = query.replace(q[qq], newq);
}
// parse jquery expressions (double brackets)
re = new RegExp('{{(.*)}}', 'g');
q = query.match(re);
for (qq in q) {
var newjq = q[qq].replace("{{", '').replace("}}", '');
code = $('<div>'+ht+'</div>').find(newjq);
appendHTML = '';
code.each(function() {
appendHTML += $(this).html();
})
query = query.replace(q[qq], appendHTML);
}
// parse %url%
ret = query.replace("%url%", url);
// ret remaining
return ret;
}
let output = parseEntry('static value %url% {{.thisclass}} {{{(\\d+)}}}', "http://perdu.com", '<h1 class="thisclass">Test</h1><h2 class="thisclass">Test2</h2> 1234 12');
console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = '&filters[]=price_gte:';
var value = 10;
How do I replace the &filters[]=price_gte:20 part with the new path? (path + value)
I've tried RegExp():
var re = new RegExp(path);
console.log(url.replace(re, ''));
//returns http://mywebsite.com/?&filters[]=price_gte:20
That didn't even work, let alone adding the digit in the regex. Problem is, price_gte is a variable (and so will price_lte be, and whatever other ranges there might come), with a variable digit after it.
Information I have:
url (http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:100)
path (&filters[]=price_gte:)
new value (10)
Desired result:
http://mywebsite.com?&filters[]=price_gte:10&filters[]=price_lte:100
What am I missing?
You were almost there, just needed to escape the brackets:
var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = '&filters[]=price_gte:';
var regexPath = '&filters\\[\\]=price_gte:\\d+';
var value = 10;
var re = new RegExp(regexPath);
console.log(url.replace(re, path+value));
Perhaps you meant this
var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = 'filters[]=price_gte:';
var value = 10;
var re = /filters\[\]=price_[g|l]te:\d+/;
alert(url.replace(re,path+value))
However a better solution might be
// from http://stackoverflow.com/a/20420424/295783
function replaceUrlParam(url, paramName, paramValue){
var pattern = new RegExp('('+paramName+'=).*?(&|$)')
var newUrl=url
if(url.search(pattern)>=0){
newUrl = url.replace(pattern,'$1' + paramValue + '$2');
}
else{
newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
}
return newUrl
}
var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var value=10;
url = replaceUrlParam(url,"filters[]", 'price_gte:'+value);
alert(url)
This seems to work for me:
function replace() {
var url = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:200';
var path = '&filters[]=price_gte:';
var value = 10;
var newStr = url.replace(/&filters\[\]=price_gte:\d+/, "&filters[]=price_gte:" + value);
alert(newStr);
}
This is enough for getting new value
var str = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:100';
var pattern = /price_gte:\d+/;
var new_value = 10;
str = str.replace(patter, 'price_gte:'+new_value);
And Simple Solution will be =>
function replace() {
var url = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:200';
var path = '&filters[]=price_gte:';
var value = 10;
var newStr = url.replace(/(\w*)(price_gte:)(\d*)/i,"price_gte:"+ value);
alert(newStr);
}
i want to strip just text values from below html with js.
var Str = "<span style="">MY name is KERBEROS.</span><B>HELLO Everbody</B>"
All text strips with codes that is below;
[^<>]+(?=[<])
But i want to strip just UPPERCASE words. Clresult must be: MY, KERBEROS, HELLO
Thank you already now for your suggestions.
Regards,
Kerberos
Here is your code, gives output: MY,KERBEROS,HELLO
<script>
String.prototype.stripHTML = function()
{
var matchTag = /<(?:.|\s)*?>/g;
return this.replace(matchTag, "");
};
String.prototype.getUpperCaseWords = function()
{
var matchTag1 = /\b([A-Z])+\b/g;
var o = this.match(matchTag1);
return o;
};
var Str = "<span style=''>MY name is KERBEROS.</span><B>HELLO Everbody</B>";
var out1 = Str.stripHTML();
var out2 = out1.getUpperCaseWords();
alert(out2);
</script>
This is another solution in JavaScript using just one line of regex:
String.prototype.stripHTML = function()
{
var matchTag = /<(?:.|\s)*?>/g;
return this.replace(matchTag, "").match(/\b([A-Z])+\b/g);
};
var Str = "<span style=''>MY name is SATYA PRAKASH.</span><B>HELLO Everyone</B>";
var out1 = Str.stripHTML();
var loc_array = document.location.href.split('/');
var linkElement = document.getElementById("waBackButton");
var newT = document.createTextNode(loc_array[loc_array.length-2]);
var repl = newT.replace('%20',' ');
linkElement.appendChild(repl);
Anyone know why this causes the text to not show up?
Why not just do
unescape(document.location.href);