javascript replace question mark - javascript

how to make a regex for ? and = in javascript?
I want something from
http://localhost/search?search=words
to
http://localhost/search/search/words
(?search=) to (/search/)
<script>
var ss = "http://localhost/search?search=words".replace("/\?search\=/g", "/search/");
document.write(ss);
</script>
BTW: just some prastic, not a htaccss rewrite. Thanks.

Almost there! = is not a special character and does not need to be escaped. In addition, regex strings are not wrapped by quotes. So:
"http://localhost/search?search=words".replace(/\?search=/g, "/search/");

How about
str.replace(/[?=]/g, "/");
Do note that it's probably better to make a function to understand the url structure and rebuild it properly, that will produce a much more healthy, robust code, rather then a simple replacement.

You can use a simple string for replace:
var ss = "http://localhost/search?search=words".replace("?search=", "/search/");

Related

Removing elements of string before a specific repeated character in it in javascript

I'm trying to remove from my string all elements before an specific character which is repeated several times in this way:
let string = http://localhost:5000/contact-support
thus I´m just trying to remove everything before the third /
having as result:contact_support
for that i just set:
string.substring(string.indexOf('/') + 3);
Bust guess thats not the correct way
Any help about how to improve this in the simplest way please?
Thanks in advance!!!
It seems like you want to do some URL parsing here. JS brings the handful URL utility which can help you with this, and other similar tasks.
const myString = 'http://localhost:5000/contact-support';
const pathname = new URL(myString).pathname;
console.log(pathname); // outputs: /contact-support
// then you can also remove the first "/" character with `substring`
const whatIActuallyNeed = pathname.substring(1, pathname.length);
console.log(whatIActuallyNeed); // outputs: contact-support
Hope This will work
string.split("/")[3]
It will return the sub-string after the 3rd forward slash.
You could also use lastIndexOf('/'), like this:
string.substring(string.lastIndexOf('/') + 1);
Another possibility is regular expressions:
string.match(/[^\/]*\/\/[^\/]*\/(.*)/)[1];
Note that you must escape the slash, since it is the delimiter in regular expressions.
string.substring(string.lastIndexOf('/')+1) will also do the job if you are looking to use indexOf function explicitly.

JavaScript global replacement

I wanna perform a global replacement by using JavaScript String replace() Method.
Original string:
<image>imageURL</image>
Result:
<img src="imageURL" />
How to achieve it? It should be similar with below code, but i don't know how to write the expression. Thanks in advance.
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
It's simpler here, you can return
text.replace(/<image>([^<]+)<\/image>/ig,'<img src="$1"/>')
Note that I didn't try to check the validity of the URL. I think it's better not to do a partial bogus check here. [^<]+ means "some characters that are not <". If you prefer, you may replace it with your URL checking regex.

How do I change this value using regex?

I have a string that's structured as so:
"http://mydomain.com/?i=0"
I'd like to be able to change the value of i using a regular expression in javascript but I'm not sure how to do it. Is anyone able to help?
Here's a place to start:
str = "http://mydomain.com/?i=0";
str = str.replace(/((?:\?|&)i=)([^&]*)/g, '$1foo');
"http://mydomain.com/?i=0".replace(/i=.*$/, 'i='+<newValue>);
if you need to cater for additional parameters following i use
"http://mydomain.com/?i=0&j=k".replace(/i=[^&]+/, 'i='+<newValue>);
there is a fiddle to demonstrate it
Use the javascript replace() function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
I'm not going to do the Regex for you as you have demonstrated no attempt at doing it yourself.
Example:
var str = "http://mydomain.com/?i=0";
var i=1; // or any other value (e.g. i="test")
str = str.replace(/i=.*/, 'i='+i);
alert(str);

How to remove `//<![CDATA[` and end `//]]>` with javascript from string?

How to remove //<![CDATA[ and end //]]> with javascript from string?
var title = "<![CDATA[A Survey of Applications of Identity-Based Cryptography in Mobile Ad-Hoc Networks]]>" ;
needs to become
var title = "A Survey of Applications of Identity-Based Cryptography in Mobile Ad-Hoc Networks";
How to do that?
You can use the String.prototype.replace method, like:
title = title.replace("<![CDATA[", "").replace("]]>", "");
This will replace each target substring with nothing. Note that this will only replace the first occurrence of each, and would require a regular expression if you want to remove all matches.
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
You ought to be able to do this with a regex. Maybe something like this?:
var myString = "<![CDATA[A Survey of Applications of Identity-Based Cryptography in Mobile Ad-Hoc Networks]]>";
var myRegexp = /<!\[CDATA\[(.*)]]>/;
var match = myRegexp.exec(myString);
alert(match[1]);
I suggest this wider way to remove leading and trailing CDATA stuff :
title.trim().replace(/^(\/\/\s*)?<!\[CDATA\[|(\/\/\s*)?\]\]>$/g, '')
It will also work if CDATA header and footer are commented.
You must perform the OPPOSITE of what was originally done to the string to ENCODE it, which was this:-
mystr='<!CDATA[' + mystr.replaceAll(']]>',']]]]><![CDATA[>') + ']]>'
All the other answers on this page that suggest "replace" without using a loop are wrong.
The regular expresion /^(<!\[CDATA\[)|(]]>)$/gm worked for me without looping.

javascript jquery regexp replace

I'm trying to create a dynamic searchbar and i need help.
Right now im trying to replace a string with another string but i cant seem to succeed.
Im getting input from the user:
var location_keyword = $("#si_user_location").val();
Now i would like to replace a whitespace " " with a "|" to use this in my regexp as OR.
For example if the user wrote "Turkey Alanya", i want it to be "Turkey|Alanya" so that the search hits for both Turkey OR Alanya.
i tried something like this but it didnt work
var location_keyword = $("#si_user_location").val();
location_keyword.replace(" ","|");
var regexp_loc = new RegExp(location_keyword, "i");
i used to do this in PHP before with expressions such as:
preg_replace('/'.preg_quote($keyword).'/i', "<span>$0</span>", $string)
and i could replace strings caseinsensetive like this, how can i do this in js?
I used the last expression in PHP to highlight the keyword in the results, which i would like to do aswell in js.
hope i can get some help, thanks in advance! :)
best of regards,
alexander
There are two problems with the use of replace on this line:
location_keyword.replace(" ","|");
It does not modify the string - it returns a new string. You need to reassign the result of the call to the original variable otherwise you won't see the changed string.
It only replaces the first occurrence unless you use a regular expression with the g (global) flag.
Try this instead:
location_keyword = location_keyword.replace(/ /g, '|');
Try this:
location_keyword = location_keyword.replace(/\s+/,"|");
This should work fine:
location_keyword.replace(/ /g,"|");
Hope this helps! :)

Categories

Resources