0

I'm trying to replace a string from a particular index to end

I have different string inputs with a link at the end I want to delete that link

for example I have :

Hello world ! this is my website link http://www.lo.com

I want to delete the link to get only :

Hello world ! this is my website link

Code :

Var message = "Hello world ! this is my website link http://www.lo.com";

How to do that in Javascript ?

8
  • Try to explore the power of regular expressions developer.mozilla.org/en/docs/Web/JavaScript/Guide/… . Commented Nov 16, 2015 at 14:14
  • 1
    Possible duplicate of Regex in Javascript to remove links Commented Nov 16, 2015 at 14:16
  • To clarify, you want the (text you have presented + the link address) to show only and the link itself to be disabled? Commented Nov 16, 2015 at 14:16
  • @MikeHorstmann I think the question is very clear.. there is no disabled link needed as you can see in the wanted result.. Commented Nov 16, 2015 at 14:17
  • Have a look at indexOf and substr or substring Commented Nov 16, 2015 at 14:18

3 Answers 3

2
var str = "Hello world ! this is my website link http://www.lo.com";

var idx = str.indexOf("http://");

str = str.slice(0,idx-1);
console.log(str);
Sign up to request clarification or add additional context in comments.

Comments

2

Here's how you do this:

message = message.substring(0, message.lastIndexOf("http://www.lo.com"));

(obs: use substring instead of substr because substr is deprecated now)

Or if you want something more general, like removing all hyperlinks at the end of the message:

message = message.replace(/(\s*(http|https):\/\/.*$)/,"");

Have fun.

1 Comment

Today substr is deprecated and you have a problemas in some browsers. Is more safe using substring Ref: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
1
function removeLinks(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, ' '); // replacing with space
}

var text = "Hello world ! this is my website link http://www.lo.com";
var corrected = removeLinks(text);
alert(corrected);

Just call the function removeLinks() which strips off the web links

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.