JavaScript global replacement - javascript

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.

Related

covering query string variations of a window.location.href

Consider the following JS code:
if ( window.location.href == "https://teamtreehouse.com/signin" ) {
// do stuff...
}
I need that the comparison operator will not only cover the exact URL, but also any possible variation of it with query strings and data coming after the phrase "signin".
How will you do that in JS? I know it should include regex but as linear learning is important for me, I would prefer waiting to my course on JS regex in the coming weeks and just ask here, in this special occasion.
Try the following regex:
/^https:\/\/teamtreehouse\.com\/signin/i
The ^ means "starting with", and the extra \ characters are just to escape special characters inside the regex.
As per the comment by #epascarello, you should definitely use the "ignore-case" parameter, i (added above).
Edit:
Use the test function:
(/^https:\/\/teamtreehouse\.com\/signin/i).test(window.location.href)
You can use String#match to check if some string contains something.
Ex:
if (window.location.href.match("https://teamtreehouse.com/signin")){
// Do something
}
Also you can use this .host & .pathname from Window.location object.
Ex:
var link = window.location.host + window.location.pathname;
if (link === "www.teamtreehouse.com/signin"){
// Do something
}
if ( /^[https:\/\/teamtreehouse.com/signin][\?[\.]+]?/.test(window.location.href)) {
// do stuff...
}

How to unescape JavaScript string literal value?

I am using regex to parse javascript code (using an ES parser, such as Esprima, is not an option for technical environment limitations).
The subject code (the code being parsed is):
(function() {
$('#3bf779cd').replaceWith("<div class=\'shows\'>\n<\/div>");
window.fadeItems();
}).call(this);
The value I am interested in is the first parameter of replaceWith, which is a string literal. I am getting this variable using regex:
const subjectValue = subjectCode.match(/\.replaceWith\(((["'])(?:(?=(\\?))\3.)*?\2)/m)[1].slice(1, -1);
console.log(subjectValue);
The output of this is:
<div class=\'shows\'>\n<\/div>
How do I escape subjectValue in a way that the output would be:
<div class='shows'>
</div>
Simply using unescape has no effect.
If I am not mistaken, the question comes does to how to unescape this value:
console.log('"<div class=\\\'shows\\\'>\\\\n<\\\/div>"');
You're looking for eval (yes you heard correctly):
text = document.querySelector('script').textContent;
dqString = /"(\\.|[^"])*"/g
s = text.match(dqString)[0]
raw = eval(s);
alert(raw);
<script>
(function() {
$('#3bf779cd').replaceWith("<div class=\'shows\'>\n<\/div>");
window.fadeItems();
});
</script>
The most idiotic way would be.
"<div class=\\'shows\\'>\\\\n<\\/div>".replace(/\\n/g, '').replace(/\\/g, '');
// "<div class='shows'></div>"
Smarter way would be to first unescape \n's than check with regex if there are unescaped matches, and than escape those as well.

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

javascript replace question mark

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

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