0

var url = new RegExp('^(https?://)?([da-z.-]+).([a-z.]{2,6})([/w .-]*)*/?$');
var title = $(".something").text().replace(url, '');

console.log(title)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="something">
Blah blah blah https://example.com/ ha ha ha.
</div>

Output I'm getting:

Blah blah blah https://example.com/ ha ha ha.

Output I want:

Blah blah blah ha ha ha.

Is the format of my expression itself wrong or the very way in which I'm trying to use regex within jQuery or something else?

I'm unable to remove URLs from the string.

3
  • Could you please give an example of the text within your .something element? What do you expect the result to be? What are you actually seeing? Commented Jul 12, 2021 at 23:16
  • "[da-z.-]" 👈 why is "d" here? It's already included in a-z Commented Jul 12, 2021 at 23:19
  • Your problem is that you are trying to match the entire string by using the start (^) and end ($) anchors. Also, /w should be \\w Commented Jul 12, 2021 at 23:33

1 Answer 1

1

I'm not able to pick apart your regex to help you there, but I am able to grab the regex I use regularly to match urls. This also removes the extra spaces afterwards.

const urlPattern = new RegExp("([a-z0-9-]+\:\/+)([^\/\s]+)([a-z0-9\-@\^=%&;\/~\+]*)[\?]?([^ \#\r\n]*)#?([^ \#\r\n]*)","g")
let title = $(".something").text().replace(urlPattern, '').replace(/\s\s+/g, ' ');
console.log('before:', $(".something").text());    
console.log('after:', title)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="something">
Blah blah blah https://example.com/ ha ha ha.
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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