How can I select all the text that appears before a url?
HTML:
<input type="text" name="field" id="field" value="Select th开发者_StackOverflow社区is text http://www.domain.com" />
JavaScript/JQuery:
$(document).ready(function()
{
var value = $('#field').val();
//select text
});
How can I select all the text
that appears before a url
? Everything after the url (including the url itself) should not be selected.
BTW, the text may also contain numbers and special characters.
Solution:
I ended up using Rocket's solution split(/\shttps?:\/\//)
(see below).
If the url will always be of the hypertext protocol, then you can do the following:
$(document).ready(function() {
var myText = $('#field').val().split(' http')[0];
});
This will capture both http and https protocols, and is the least computing-intensive approach as far as I can tell.
The text is just a string. You need to identify what makes the URL part of it unique - starting http:// ( making sure it is not https:// ), including www., or whatever. Once you have identified what matches the url and not the other characters before this, then it is easy.
Use the java objec Regexp. This will allow you to use pattern matching and select the text based on the url pattern.
here is a tutorial on javascript RegExp object: http://www.w3schools.com/jsref/jsref_obj_regexp.asp
and this is a good javascript RegExp tester: http://www.regular-expressions.info/javascriptexample.html
Let me know if you have any troubles with the regexp!!
精彩评论