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

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?

Related

Match strings using asterisks (wildcards) [duplicate]

This question already has answers here:
Wildcard string comparison in Javascript
(10 answers)
Closed 4 years ago.
I want to test if any string in an array matchs with a particular string. However, the strings in array may contain the asterisks pattern.
var toTest = ["foo_*", "*foo_1", "foo_1*", "bar", "*foo"];
var toMatch = "foo_1";
For this sample, the result will be true because foo_*, *foo_1 and foo_1* will match with foo_1, but bar and *foo won't.
I have tried to use split function with lodash _.some but it seems overcomplicated and I can't make it works consistently.
function isMatching() {
return _.some(toTest , function(a) {
return _.some(a.split("*"), function(part1, idx1) {
return (part1.length && _.some(toMatch.split(part1), function(part2, idx2) {
return (part2.length && idx1 == idx2);
}));
});
});
}
To achieve expected result, use below option of using filter, indexOf and replace
var toTest = ["foo_*", "*foo_1", "foo_1*", "bar", "*_foo"];
var toMatch = "foo_1";
console.log(toTest.filter(v => toMatch.indexOf(v.replace('*', '')) !== -1))

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

Javascript get the string between two symbols [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 years ago.
I have the following string and I'm trying to retrieve the string between two symbols
http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_search&wpv-women-clothing[]=coats
I need to retrieve wpv-women-clothing[] or any other string between the last & and the last = in the URL
Should I use regex for this or is there a function in Javascript/jQuery already well suited for this?
Thanks
var str = "http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_search&wpv-women-clothing[]=coats";
var last =str.split('&').pop().split('=')
console.log(last[0]) // wpv-women-clothing[]
jsFiddle example
Split the string on the ampersands (.split('&')), take the last one (.pop()), then split again on the = (.split('=')) and use the first result last[0].
.*&(.*?)=.*
This should do it.
See demo.
http://regex101.com/r/lZ5bT3/1
Group index 1 contains your desired output,
\&([^=]*)(?==[^&=]*$)
DEMO
> var re = /\&([^=]*)(?==[^&=]*$)/g;
undefined
> while ((m = re.exec(str)) != null) {
... console.log(m[1]);
... }
wpv_post_search&wpv-women-clothing[]
Can you try:
var String = "some text";
String = $("<div />").html(String).text();
$("#TheDiv").append(String);

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

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
}

Categories