Check if the string ends with a question mark using jquery [duplicate] - javascript

This question already has answers here:
How to get the last character of a string?
(15 answers)
Closed 8 years ago.
How can check the entered input is a valid question format using jquery ?
for eg: i have a string "How are you ?" . and i need to identify whether it is a
question or not .Do that all i need is to check whether the string ends with '?' ?. Thanks .

This will do the trick...
if (value.substr(-1) === "?") {
// do what you need here
}
string.substr(x) will start at the character with index x and go to the end of the string. This is normally a positive number so "abcdef".substr(2) returns "cdef". If you use a negative number then it counts from the end of the string backwards. "abcdef".substr(-2) returns "ef".
string.substr(-1) just returns the last character of the string.

If you want a cute endsWith function:
String.prototype.endsWith = function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
};
console.log('Is this a question ?'.endsWith('?')); // true
Took the answer here.

You can use \?$ regex to find strings ending with ? mark.
var str = "what is your name?";
var patt = new RegExp("\? $");
if (patt.test(str))
{
// do your stuff
}

Related

JavaScript - Is there a way to check if a string includes a keyword but only that keyword? [duplicate]

This question already has answers here:
Javascript find index of word in string (not part of word)
(3 answers)
Closed 5 years ago.
I'm currently using the string.includes() method to check for the keyword 'rally' in a string. But if I have the text 'Can I have a rally?', it will respond the same as 'Am I morally wrong?'. Is there a way to do this?
try this
'Can I have a rally?'.match(/(\w+)/g).indexOf("rally") !== -1 // will return true
'Am I morally wrong?'.match(/(\w+)/g).indexOf("rally") !== -1 // will return false
edit Using regular expressions
let text = "Am I mo rally wrong";
function searchText(searchOnString, searchText) {
searchText = searchText.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
return searchOnString.match(new RegExp("\\b"+searchText+"\\b", "i")) != null;
}
console.log(searchText(text, "rally"));
maybe you just add space. So morally gives false result. This checks the words possible each position into sentence also whole string is "rally".
var string = "Can I have rally";
console.log(string==="rally" ? true : false || string.includes(' rally') || string.includes('rally ') || string.includes(' rally '));

Get duplicate characters count in a string [duplicate]

This question already has answers here:
Counting frequency of characters in a string using JavaScript [duplicate]
(21 answers)
Closed 7 years ago.
Can anyone help me to get the count of repeated characters in a given string in javascript.
For example,
"abccdef" -> 1 (Only "c" repeated)
"Indivisibilities" -> 2 ("i" and "s" repeated)
Thank You
You can use like this
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
getFrequency('Indivisibilities');
This is an interesting problem. What we can do is turn the string to lower case using String.toLowerCase, and then split on "", so we get an array of characters.
We will then sort it with Array.sort. After it has been sorted, we will join it using Array.join.
We can then make use of the regex /(.)\1+/g which essentially means match a letter and subsequent letters if it's the same.
When we use String.match with the stated regex, we will get an Array, whose length is the answer. Also used some try...catch to return 0 in case match returns null and results in TypeError.
function howManyRepeated(str){
try{ return str.toLowerCase().split("").sort().join("").match(/(.)\1+/g).length; }
catch(e){ return 0; } // if TypeError
}
console.log(howManyRepeated("Indivisibilities")); // 2

Find a word (not a character ) in a string? [duplicate]

This question already has answers here:
Determining whether a string has a substring (word)
(5 answers)
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 8 years ago.
This is my JavaScript code :
var a = 'how are you';
if (a.indexOf('r') > -1)
{
alert('yes');
}
else {
alert('no');
}
This code alert('yes'). It only matches the character 'r' is present in the string or not. But I want to match a full word(like 'are') not a character. How I can do this?
Read MDS
str.indexOf(searchValue[, fromIndex])
searchValue
A string representing the value to search for.
fromIndex
The location within the calling string to start the search from. It can be any integer between 0 and the length of the
string. The default value is 0.
So (a.indexOf('are') > -1) should work that will return 4 for a = 'how are you'.
You can also use a.search("are").
var a = 'how are you';
if (a.search('are') > -1)
{
alert('yes');
}
else {
alert('no');
}
like this
var str = "how are you";
var n = str.search("are");
or do u want algorithm?

RegEx extract all real numbers from a string [duplicate]

This question already has answers here:
Regex exec only returning first match [duplicate]
(3 answers)
Closed 8 years ago.
This regex in JavaScript is returning only the first real number from a given string, where I expect an array of two, as I am using /g. Where is my mistake?
/[-+]?[0-9]*\.?[0-9]+/g.exec("-8.075090 -35.893450( descr)")
returns:
["-8.075090"]
Try this code:
var input = "-8.075090 -35.893450( descr)";
var ptrn = /[-+]?[0-9]*\.?[0-9]+/g;
var match;
while ((match = ptrn.exec(input)) != null) {
alert(match);
}
Demo
http://jsfiddle.net/kCm4z/
Discussion
The exec method only returns the first match. It must be called repeatedly until it returns null for gettting all matches.
Alternatively, the regex can be written like this:
/[-+]?\d*\.?\d+/g
String.prototype.match gives you all matches:
var r = /[-+]?[0-9]*\.?[0-9]+/g
var s = "-8.075090 -35.893450( descr)"
console.log(s.match(r))
//=> ["-8.075090", "-35.893450"]

How to trim a string to its last four characters? [duplicate]

This question already has answers here:
How to get the last character of a string?
(15 answers)
Closed 8 years ago.
I know there are methods to remove characters from the beginning and from the end of a string in Javascript. What I need is trim a string in such a way that only the last 4 characters remain.
For eg:
ELEPHANT -> HANT
1234567 -> 4567
String.prototype.slice will work
var str = "ELEPHANT";
console.log(str.slice(-4));
//=> HANT
For, numbers, you will have to convert to strings first
var str = (1234567).toString();
console.log(str.slice(-4));
//=> 4567
FYI .slice returns a new string, so if you want to update the value of str, you would have to
str = str.slice(-4);
Use substr method of javascript:
var str="Elephant";
var n=str.substr(-4);
alert(n);
You can use slice to do this
string.slice(start,end)
lets assume you use jQuery + javascript as well.
Lets have a label in the HTML page with id="lblTest".
<script type="text/javascript">
function myFunc() {
val lblTest = $("[id*=lblTest]");
if (lblTest) {
var str = lblTest.text();
// this is your needed functionality
alert(str.substring(str.length-4, str.length));
} else {
alert('does not exist');
}
}
</script>
Edit: so the core part is -
var str = "myString";
var output = str.substring(str.length-4, str.length);

Categories