Reputation: 1345
i want to check particular character occurrence in a string java script,
following is what i need
it is a object
var text = 'ABC.DEF';
()
at the very end
of the string i have to alert it is a function
var text = 'ABC()';
i tried this
if(text .indexOf('()') === -1)
{
alert("not function");
}
but how i can check whether brackets are in very end.
Upvotes: 0
Views: 174
Reputation: 168730
The regular expression ^\w+\.\w+$
will match a string consisting of:
Similarly, the regular expression ^\w+\(\)$
will match a string consisting of:
You can wrap it in a function like this:
function check( text_to_match ){
if(text_to_match.match(/^\w+\.\w+/))
console.log("it is an object ");
else if(text_to_match.match(/^\w+\(\)$/))
console.log("it is an function");
}
Upvotes: 1
Reputation: 293
You an use RegEx:
var one = "ABC.DEF";
var two = "ABC()";
var three = "()blank";
function check(string){
// Matches: ABC.DEF and Does not match: ABC. or .DEF
if(/\w+\.\w+/.test(string))
console.log("it is a function");
// \(\) interpreted as (). Matches : ABC() ; Does not match: ()ABC or ABC()ABC
else if(/\w+\(\)$/.test(string))
console.log("it's an object");
// Not found
else
console.log("something else")
}
check(one); // it is a function
check(two); // it's an object
check(three); // something else
The $
checks if the match(()
) is at the end of the line.
The \w+
is count one or more occurrences of "A-Za-z0-9_"
.
Upvotes: 3
Reputation: 66404
String.prototype.slice
lets you use negative numbers to tackle the other end of the String.
'foobar'.slice(-2); // "ar"
so
if (text.slice(-2) === '()') {
// last two digits were "()"
}
Upvotes: 0
Reputation: 7326
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
if("ABC()".indexOf("()") > -1) {
alert("it is a function");
}
if("ABC.DEF".indexOf(".") > -1) {
alert("it is an object");
}
if("ABC()".endsWith("()")=== true) {
alert("ends with ()");
}
if("ABC()".endsWith("()whatever")=== true) {
alert("ends with ()");
}
Upvotes: 1
Reputation: 25537
try
var a = "abc()";
if (a[a.length-1] == ')' && a[a.length - 2] == '(') {
alert("function");
}
Upvotes: 1
Reputation: 1136
Try this:
if(text.substring(2) == "()")
{
alert("it is function");
}
Upvotes: 0
Reputation: 9279
indexOf returns the position of the string in the other string. If not found, it will return -1:
var s = "foo";
alert(s.indexOf("oo") != -1);
Upvotes: 0