ismail vittal
ismail vittal

Reputation: 175

Javascript - Append character and replace together

Please help me to achieve the below

Ex: http://www.something.com is my text in a textbox "txtSource"

I want to replace the above "http://www.something.com" with http://nothing.nothing.something.com where, www. should be ommitted and "nothing.nothing" should be added for whatever url I mention in the txtSource.

In other way, Its just a matter of replacing www. with nothing.nothing Please help me to achieve the same.

Upvotes: 0

Views: 479

Answers (4)

puk
puk

Reputation: 16782

If you are asking about replacing strings, then never use web link formats ('www.exam...') It would be like using measurements of distance to describe time (see 'parsecs').

If you are indeed talking about changing the actual website shown in the web browser, then you can use mod_rewrite to redirect web links.

The user would enter

www.example.com/index.html

and mod_rewrite would display it as

www.example.com

Upvotes: 0

Some Guy
Some Guy

Reputation: 16210

If you're certain that the URL is all that will be there in the textbox, you can do this with something as simple as this:

var box = document.getElementById('txtSource');
box.textContent = box.textContent.replace('www', 'nothing.nothing');

The 'www' could be a Regular Expression instead, but since you're just searching for one instance of 'www' you can use what I've shown above. You may want to add the case-insensitive modifier so it'll replace URLs like http://wWw.something.com as well. To do that, you'd use this:

box.textContent = box.textContent.replace(/www/i, 'nothing.nothing');

Read more about Regular Expressions here

Demo

Upvotes: 1

lgomezma
lgomezma

Reputation: 1637

You can do it by using the javascript function for strings .replace() like this:

var str='http://www.something.com';

var newstr = str.replace(/www/i,'nothing.nothing'); 

What you are doing here is to provide a regular expression that matches what you want to replace and the string to replace it. The '/' of the /www/i acts as an indicator of the beginning and the end of the regular expression, and the 'i' makes it case-insensitive.

Upvotes: 0

fardjad
fardjad

Reputation: 20404

assuming you mean input by text box:

var input = document.getElementById('txtSource');
input.value = input.value.replace(/www/i, 'nothing.nothing');

Upvotes: 0

Related Questions