How do I replace characters using Javascript in HTML file? - javascript

For example I have a string getting from current URL using javascript
hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc
How do I replace character in the end OrderDateAsc ? If I want to replace for example , OrderDateDesc , how should I do it using Javascript ? The URL infront might be differs all the time , they keyword should be &sortBy.
Please help ,thanks.

var currentUrl = window.location.href;
var url = new URL(currentUrl);
var c = url.searchParams.get("sortBy");
You can get sortBy value like this, and maybe you can use some if statements for if set or not , and you can set like this:
url.searchParams.set('sortBy',"WhateverYouWant");
Also,convert url to string, you can read parameters url.searchParams.get("sortBy"); and again some if statements,
if change :
url = url.Replace(sortByValue,"WhateverYouWant");
this will works too.
But if your string looks like that and you try to change search value, then you will change every "search" value and its not work. :
hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc
change search as WhateverYouWant
hostname/report/WhateverYouWantDate?WhateverYouWantOrderID=&WhateverYouWantDateFrom=2018-10-16&WhateverYouWantDateTo=2018-10-23&WhateverYouWant=WhateverYouWant&sortBy=OrderDateAsc
You see, its bad :)

You could do it with the following code.
//your string
let str = "hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc";
//find "OrderDateAsc" and replace it with "OrderDateDesc"
str = str.replace("OrderDateAsc", "OrderDateDesc" );

you can use regular expression and replace the sortBy param value like that:
const url ='hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc';
const regex = /(&sortBy=OrderDate)(Asc)/gi;
const newUrl = url.replace(regex, '$1Desc');

Related

How to add a variable to a regex checking for a URL?

I have this part of a function which is running perfectly:
if(/https?:\/\/[a-z]{2}w?\.mywebsite\./.test(href)){
if(!firstSerp){
firstSerp = this;
add_prerender(this, href);
}
}
As you can see mywebsite is hard-coded. What I want is to put a variable there instead.
So it would look like this:
var mylink = 'mywebsite';
if(/https?:\/\/[a-z]{2}w?\.+= mylink\./.test(href)){}
One of the users suggested I look at How do you use a variable in a regular expression?
var replace = "regex";
var re = new RegExp(replace,"g");
But I have difficulties understanding how that would apply to my example.
Could you please help me solve this?
Regular expressions are intended to be used to check if an existing string matches a pattern or to find a pattern in an existing string. You cannot use them to build a string.
Instead, you should use string concatenation:
const url = 'http://www.' + mywebsite + '.com';
or a string template:
const url = `http://www.${mywebsite}.com`;

Find and replace a substring after a word in javascript

I have a string which has email id as plain text in it ,I want to replace the email id in the string with hashed value eg.
var str ="Token=wUFvvW4pLDjO2Kh9BkF6ShNXMpWCAH84RQrF2GMSMvkT9ji1HWER/hPcDzQVZ+eqfBnzltOP0+NJTa/x6+XrKcSR090Jka8Awdj13CiSiD5OXwFbCHzYX0nzwkbWJ3m7zvyvjIWJJZ7L53YRHckAeTzA39UWR53/s8PHyL7hUu8=&ssoComplete=true&userId=testmail5#gmail.com|flca+&siteID=OXchfjbB"
Before storing the above string I want to hash only testmail5#gmail.com which is after userId=. Hence need suggestions to achieve the same.
Using split twice
var str="Token=wUFvvW4pLDjO2Kh9BkF6ShNXMpWCAH84RQrF2GMSMvkT9ji1HWER/hPcDzQVZ+eqfBnzltOP0+NJTa/x6+XrKcSR090Jka8Awdj13CiSiD5OXwFbCHzYX0nzwkbWJ3m7zvyvjIWJJZ7L53YRHckAeTzA39UWR53/s8PHyL7hUu8=&ssoComplete=true&userId=testmail5#gmail.com|flca+&siteID=OXchfjbB"
console.log(str.split('userId=')[1].split('|')[0])
Try this :
str.match(/\userId=(.*?)\|/)[1]
Regex are better to do stuff like that
Quick and dirty way by using URL API in JS.
var data = "Token=wUFvvW4pLDjO2Kh9BkF6ShNXMpWCAH84RQrF2GMSMvkT9ji1HWER/hPcDzQVZ+eqfBnzltOP0+NJTa/x6+XrKcSR090Jka8Awdj13CiSiD5OXwFbCHzYX0nzwkbWJ3m7zvyvjIWJJZ7L53YRHckAeTzA39UWR53/s8PHyL7hUu8=&ssoComplete=true&userId=testmail5#gmail.com|flca+&siteID=OXchfjbB";
var some_hash = "myHashValue";
var data_url = new URL("http://localhost/?"+data); // dirty part
var new_data = data.replace(data_url.searchParams.get("userId").split('|')[0], some_hash);
console.log(new_data);

Regular Expression Error with Match() Method

I am using a regular expression to capture a URL string, but it's not working out.
Here's my code, which is coming from an external JavaScript document, linked to the HTML file:
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/;
var urlRegMatch = url.match(urlRegEx);
document.write(urlRegMatch);
The output that I get is this: "www.google.com,www.,,www."
What am I doing wrong?
Thanks! :)
Your regex works fine, what happens is that according to the match function you are getting one extra result for each group (defined by these parenthesis) that you have in your regex. to access the whole match you can access to the first item of the match return like the following:
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/;
var urlRegMatch = url.match(urlRegEx)[0]; //this line changed, im using [0] to access the whole match only
document.write(urlRegMatch);
working example: https://jsfiddle.net/2sptg5rz/3/
reference about the match function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match#Return_value
I'd like to thank #Dknacht and #Tressa for directing me to the correct answer, since the first value of the array, 0, is the matched text.
This code works for what I want to do:
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/
var urlRegMatch = url.match(urlRegEx);
document.write(urlRegMatch[0]);

regex parsing a dynamic parameter from url string

I have a URL as follows: www.mysite.com?paramNamePrefixXXX=value
What is the best way to parse the url for the parameter name / value where XXX is dynamic/unknown..
Since I don't know the parameter name at render time.. I'd like to match on the 'startswith.. 'paramNamePrefix' + XXX (where XXX is some string..) and return the value
jquery offer a simple way to do this?
var url = "http://www.mysite.com?foo=bar&paramNamePrefixXXX=value&fizz=buzz",
prefix = "paramNamePrefix";
var desiredValue = url.match(new RegExp('[?&]' + prefix + '.*?=(.*?)[&#$]', ''));
desiredValue = desiredValue && desiredValue[1];
console.log(desiredValue); // -> "value"
Demo
This will parse it I believe. The only issue you would run into with the way it's written is if there was an = sign in your parameter value somehow.
((?<=&|\?).+?)(?<=\=)(.+?(?=&|$))
basically I've got it in 2 reference groups
((?<=&|\?).+?) <-- captures parameter name using a look behind
(?<=\=)
(.+?(?=&|$)) <-- captures parameter value using a look ahead

How to convert jquery attr value to a string object to use it as a regex expression?

i want to search a string variable if it contains a jQuery object's attr value. I have tryed this:
var txt = "lets go to a.html";
var searchText = new RegExp($("#link").attr("href"));
alert(txt.search(searchText)>=0);
but this always returns false.
im sure that $("#link").attr("href") returns "a.html" as value.
also i have tried this if i was doing something wrong,
var txt = "lets go to a.html";
var searchText = new RegExp("a.html");
alert(txt.search(searchText)>=0);
this time it has returned true.
i thought jquery was not returning a string object and i have tried to turn it to string like this:
var txt = "lets go to a.html";
var searchText = new String($("#link").attr("href"));
searchText = new RegExp(searchText);
alert(txt.search(searchText)>=0);
this has aslo returned false..
when i used toString($("#link").attr("href")) it always returns true even attr value is not "a.html"
anyone can help me on this?
thank you.
Do this:
var txt = "lets go to a.html";
var searchText = $("#link").attr("href");
alert(txt.indexOf(searchText) !== -1);
To create a regular expression from a string:
var re = new RegExp('your string');
To see if it matches another string:
re.test('another string'); // false
re.test('here is your string'); // true
Note though that some characters must be escaped, so to match a whitespace:
var re = new RegExp('\\s');
In your case, you should reverse the sense of the test:
searchText.test(txt)
which will return true if 'a.html' is in txt.
Depending on what browser you are testing in the href attribute, when queried through jQuery, will return a fully qualified url even tho you have set it to a relative url.
Test to make sure that $('#link').attr('href') actually returns a.html and not http://url/a.html.
Okay problem is solved i must say sorry to everyone who spent time to solve this problem
problem was on my html :(
i have putted an emty character inside the href attribute like this:
<a href="a.html ">
the codes i have given all are working well :)

Categories