How to Find and Replace word from URL in JQuery? - javascript

i have come through many relevant questions but my scenario is different. . . . . . . . . . . . . .
I have this URL Address:
http://www.domain.com/word-one/word-two/word-three/word-four
there are 4 words after slash in my URL, and i want find 'word-three' replace it with anything.
How can i do it with Jquery on Click event.
Any help will be appreciated. Thanks
(Edited)
There is something i forgot to mention that is word-three is not hard coded maybe something else at this place. So the thing is We have to change the word after 3 Slashes.

If you want to replace 'word-three' with 'edited'
var url = "http://www.domain.com/word-one/word-two/word-three/word-four";
url.replace(url.split('/')[5], 'edited');

Try this:
var url = "http://www.domain.com/word-one/word-two/word-three/word-four"
var array = url.split("/");
console.log(array);
array[5] = "someOtherWord";
var new_url = array.join("/")
console.log(new_url)
console.log for debugging purposes.
View on Fiddle:
Edit:
I'm assuming here you know how to wrap this into onclick event. Also, you will need to pass your url somehow to the event handler. There is more than one way of doing that depending on your code, and where the url comes from.

You don't need jQuery..
1.Use .replace (but it only replaces the first occurrence, not all occurrences)
var url = "http://www.domain.com/word-one/word-two/word-three/word-four";
url.replace('word-three','somex');
//result "http://www.domain.com/word-one/word-two/somex/word-four"
2.For replacing multiple occurrences, use split & join
var url = "http://www.domain.com/word-one/word-two/word-three/word-four";
url.split('word').join('somex');
//result "http://www.domain.com/somex-one/somex-two/somex-three/somex-four"

Related

JS / Node.js string().replace() help also help editing URL

I am trying to edit a string in Node.js. I am developing a web proxy, and I need to rewrite some stuff.
What I need to rewrite is when there is two querystrings in a URL.
I just need the first one to stay but the rest to be modified to "&".
This is what I got.
.replace(new RegExp(/src="(.*?)?(.*?)?&_get=/gi),'src="$1' + '$2' + '&_get=')
But it's not replacing the querystring but the replace is working.
I also need this in string.replace() specifically. If this is not possible, I would like to know how I can get a URL to redirect to a link that replaces the querystring except the first one.
Based on your input output example in the comments, it seems like there's lots of ways you could do this.
One way would be to find the index of the last "?" and use the substring method to "replace" it.
let str = "balalala?query?_get=https://example.org"
let ind = str.lastIndexOf("?")
let newStr = str.substring(0,ind) + "&" + str.substring(ind+1)
If balalala? is always going to be constant, you can separate that out.
var source = 'balalala?'
var str = 'balalala?query?_get=https://example.org'
var rest = str.replace(source, '');
console.log(`${source}${rest.split('?').join('&')}`);

Replacing URLS with Hyperlinks

I found the following function:
function addHyperlinks(str) {
// Set the regex string
var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig
// Replace plain text links by hyperlinks
var replaced_text = str.replace(regex, "<a href='$1' target='_blank'>$1</a>");
// Echo link
return replaced_text;
}
Which works okay, however when there is a dash in the URL it stops processing there. So for instance, the following URL:
http://website.com/some-internet-page
Will get replaced with:
<a href='http://website.com/some'>http://website.com/some</a>-internet-page
I'm not good with regex, could anyone help modify the above so that this doesnt happen?
#Tonny said it in the comments above:
/(https?://([-\w-.]+)+(:\d+)?(/([\w-/_.]*(\?\S+)?)?)?)/ig
Thank you!

Match #(\w+) and replace in javascript

I'm trying to match #(\w+) in a div content and remove it.
Here's what i've tried : http://jsfiddle.net/mxgde6m7/1/ .
#(\w+) works , but it doesn't replace with space.
var content = document.getElementById('contentbox');
var find = '#(\w+)';
var reg = new RegExp(find, 'g');
var result = content.innerHTML.replace(reg, ' ');
alert(result);
<div id="contentbox">#d test
What i want: <div id="contentbox">test
</div>
Thanks in advance.
EDIT
Okay, one problem solved, another one came up.
My script http://jsfiddle.net/mxgde6m7/9/ works perfectly there, but when i try it on my website, only a half works. The last part where it should replace #(\w+) with space doesn't work at all. If i copy/paste the CONTENT of the function in console(chrome), it works , but if i paste the function and i call it, it doesn't work.
Please help ! I'm stuck.
Using a RegExp constructor, you need two backslashes \\ in place of each backslash \.
var find = '#(\\w+)';
hwnd is correct that you need to double escape \w in your regular expression.
var find = '#(\\w+)';
But, you could also make this code much cleaner by defining a regex literal like so -
var content = document.getElementById('contentbox');
var result = content.innerHTML.replace(/#(\w+)/g, ' ');
alert(result);
Doing it this way doesn't require double escaping, as it's not a string.

jquery .replace(/./g, "") do not work for me but others

I found this snippet somewhere and it works like a charm:
var n = parseInt(e.find("span.favNum").text().replace(/./g, "")) + 1;
If I do it in a similar way it doesn't work anymore.
I do the following:
<div id ="test">6.987</div>
var test = $("#test");
var r = test.text().replace(/./g, "");
console.log("wrong ", r);
I know that I can replace it also like this:
var r = test.text().replace(".", "");
This works.
I would like to understand why the "stolen" snippet is working.
Any idea?
http://jsfiddle.net/nJZMf/3/
The original script is found here: http://wp-svbtle.themeskult.com/
You will find the snippet by viewing the source of index.html and searching for .replace.
You need to escape the "."
test.text().replace(/\./g, "");
The reason that the code in the page you linked to works, where yours doesn't, is that it's not the same regular expression. Here's what I found in that page (and similar code in several places)
r = n.text().replace( /,/g, "" )
where r is a jQuery object.
Note that the regular expression has a , inside the //, not a . like the code you had trouble with.
Comma is not a special character in regular expressions, so it needs no special treatment. Period has a special meaning. As the other answers pointed out, it matches all characters, and you need to prefix it with \ if you want to match . only.
Also note that .replace() is not jQuery code, it's JavaScript.
jQuery's .text() method returns a JavaScript String value. So anything you do with that string - such as the .replace() call - is actually a JavaScript String method.
The distinction is important when you want to research a problem: a search for "javascript string replace" will get you better information than "jquery replace".
It has to be var r = test.text().replace(/\./g, ""); instead of var r = test.text().replace(/./g, ""); because you need to escape the . in order for it to be replaced.
http://jsfiddle.net/mrk1989/nJZMf/4/
Solution because I add \ in var r = test.text().replace(/\./g, "");
The problem was that you did not escape dot.
But keep in mind that:
.replace(".", "");
.replace(/\./g, "");
are two different things.
For example: https://jsfiddle.net/rmhpkz9n/1/

Match URL's which do NOT have a specific prefix

i match image urls inside a string with the following regular expression in javascript:
/\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|]?(\.(jpe?g|png|gif))/ig
with the String.replace function, i wrap all matches inside an -tag.
in a second step i'd like to match all urls, which do not have the above file extensions as prefix. my first intention was to use the ?!-operator like this:
/\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|]?(?!\.(jpe?g|png|gif))/ig
unfortunatly, this does no work. tried different variations of this expression, but with now results.
thanks for any help in advance,
manuel
Since you're asking about javascript, I think something like this could help :
var url_re = "\\b(https?|ftp|file):\\/\\/[\\-A-Z0-9+&##\\/%?=~_|!:,.;]*[\\-A-Z0-9+&##\\/%=~_|]?"
var re = new RegExp( "^(?!.*"+url_re+"\.(jpe?g|png|gif)).*"+url_re+"\.[a-z0-9_]+" , 'gi' )

Categories

Resources