PDA

View Full Version : A code that detects if a value start with something (?)



bladefinor
12-16-2008, 07:52 PM
A textfield has the value "http://www.google.com/".
I want to have a javascript that detects if the value starts with "http://", because then it will do "alert('The value starts with http://')". Or if the textfield's value is something else, it should do "alert('Nothing special...')"

How to do this?

Twey
12-17-2008, 12:16 AM
String.prototype.startsWith = function(s) {
return this.substr(0, s.length) === s;
};
"http://www.google.com/".startsWith("http://") // true
"http://www.google.com/".startsWith("google") // false

bladefinor
12-17-2008, 12:12 PM
I don't get it.
Where do I put this?

Or should i do like this?


function goButton(){
String.prototype.startsWith = function(s){
return this.substr(0, s.length) === s;
}
if(document.getElementById('addressBar').value.startsWith == "http://"){
alert('The value starts with http://');
}
}

I don't think so... But I don't understand what you mean by just posting the code :S
But i'm appreciating your help :)

rangana
12-17-2008, 12:23 PM
Implementation from Twey's prototype:


<script type="text/javascript">
String.prototype.startsWith = function(s) {
return this.substr(0, s.length) === s;
};
function goButton(el,string)
{
alert(document.getElementById(el).value.startsWith(string)?'The value starts with '+string:'It doesn\'t starts with '+string);
}
</script>
<input type="text" id="inp"><input type="button" onclick="goButton('inp','http://')" value="Check Start">

Twey
12-17-2008, 01:17 PM
String.prototype.startsWith = function(s){
return this.substr(0, s.length) === s;
};

function goButton() {
if (document.getElementById("addressBar").value.startsWith("http://"))
alert("The value starts with http://");
}

bladefinor
12-17-2008, 01:59 PM
yeah thx, i figured it out myself :)
thx guys!