Use "^" to check if string begins with another string? [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
javascript - check if string begins with something?
I've read in this post that you can use ^= to check if a string begins with something.
I've fiddled with this example:
var foo = "something-something";
if(foo ^= "something") {
alert("works!");
}
else{
alert("doesn't work :(");
}
And it doesn't work - does anyone how to do this?
jsfiddle example here: http://jsfiddle.net/timkl/M6dEM/

I think, perhaps, you were thinking of:
var x = "hello world!"
if (x.match(/^hello/)) {
alert("I start with it!")
}
This uses an anchored (^) regular expression: it must find "hello" at the start of the input to match.
On the other hand, x ^= "foo" is the same as x = x ^ "foo", or a bit-wise exclusive or. In this case that is equivalent to x = "something-something" ^ "something" -> x = 0 ^ 0 -> 0 (which is a falsey value, and never true).
Happy coding.

var foo = "something-something";
if(foo.indexOf("something") === 0) {
alert("works!");
}
else{
alert("doesn't work :(");
}
See updated jsfiddle http://jsfiddle.net/M6dEM/3/

Use substring() method.
if(foo.substring(0,"something".length) == "something") {
alert("works!");
}
else{
alert("doesn't work :(");
}
I edited my answer and replaced "9" with "something".length so now there's no hardcode anymore.

Related

jquery regex continuous space [duplicate]

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 5 years ago.
I want to check input and want to show error if input is empty or entered continuous space. just one space allowed between words. e.g:
Test ok test
var pattern = /\s\s+/g;
$('a').click(function() {
if ($('input').val().length <= 2 || pattern.test($('input').val())) {
alert('error');
} else {
alert('ok go');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>check</a>
<input type="text"/>
It seems working, but it have issue, do this to find this issue:
Enter 5 space continuously, then click on check, it alert error but click again on check, it alert ok.
should error when user entered more than 2 space continuously.
you can use trim method which will work better than your code in the if statement .
The trim() method removes white space from both ends of a string which in this case the value of the input , after that you can check if its equal to the empty string and will work fine
see the example below
var pattern = /\s\s+/g;
$('a').click(function() {
if ($('input').val().trim()==='') {
alert('error');
} else {
alert('ok go');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>check</a>
<input type ="text" />
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test:
If the regex has the global flag set, test() will advance the lastIndex of the
regex. A subsequent use of test() will start the search at the substring of str
specified by lastIndex (exec() will also advance the lastIndex property).
The problem is after your regex is matched against the string, the lastIndex property will cause the next match to start after the previous match. You can verify this by outputting the value of pattern.lastIndex after each click.
You can fix this by manually setting lastIndex back to zero after each match, like
$('a').click(function() {
pattern.lastIndex = 0;
if ($('input').val().length <= 2 || pattern.test($('input').val())) {
alert('error');
} else {
alert('ok go');
}
});
You can also fix by getting rid of pattern all together and writing
$('a').click(function() {
if ($('input').val().length <= 2 || /\s\s+/g.test($('input').val())) {
alert('error');
} else {
alert('ok go');
}
});
Note that you can change your pattern to /\s{2,}/g matching whitespace two or more times.

How to remove all non-alphabet characters, javascript [duplicate]

This question already has answers here:
Java, Check if a String is a palindrome. Case insensitive
(5 answers)
Closed 5 years ago.
I am asked to check if a string is a Palindrome.
To not be case sensitive. To ignore all characters that are not letters.
My Answer
function palindrome(str) {
var oldStr = str.toLowerCase().replace(/\s+|\,|\.|\_|\-|\:|\(|\)|\/|\\/g, '');
var newStr = str.replace(/\s+|\,|\.|\_|\-|\:|\(|\)|\/|\\/g, '').split("").reverse().join("").toLowerCase();
if ( oldStr === newStr){
return true;
}
else {
return false;
}
}
palindrome("ininiNI");
The function is to be checked with any string possibility.
Example: ("0_0 (: /-\ :) 0-0") Which according to the requirements should return true.
I could not find a better solution in JavaScript then the one above.
Is there a faster/better way than just writing out each possible character to be removed/replaced? (especially since what I wrote is far from exhaustive...)
There is no need to call toLowerCase() and replace() twice. You can also cut string in a half, reverse one part and then compare. That way you can speed up your function few times at least.
Optimized function may look like that:
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-z]/g, '');
var max = str.length - 1;
for (var i = Math.floor(max / 2); i >= 0; i--) {
if (str[i] != str[max - i]) {
return false;
}
}
return true;
}
palindrome("inabcbani"); //true
palindrome("abcddcba"); //true
palindrome("a*#$(b)&^#%#%(*a"); //true
palindrome("abba"); //true
palindrome("abcdba"); //false
For loop will be the fastest way in my opinion as it's quick and simple. You can return false once you find first character that doesn't match.

How to check if a value of the input is number or not? [duplicate]

This question already has answers here:
Validate decimal numbers in JavaScript - IsNumeric()
(52 answers)
Closed 8 years ago.
I have this problem here, I want to check if the value of the input is going to be a number or not on keyup. Any help would be appreciated.
$('input').keyup(function () {
var check_nm = $('input').val();
if(check_nm != "123"){
console.log('not number');
}else{
console.log('is number');
}
});
jsfiddle
$('input').keyup(function () {
var check_nm = $('input').val();
if (isNaN(check_nm) || check_nm.trim() == "") {
console.log('not number');
}else{
console.log('is number');
}
});
Use a combination of isNaN and.trim() == "" to ensure that blank spaces are not counted as numbers
You can also use isNaN(parseFloat(check_nm)) or $.isNumeric(a), which basically runs isNaN(parseFloat())
you can check if the number is NOT a number by calling isNaN(num) so if you want the opposite it will be !isNaN()
You can use unary operator + to convert the value to a number. And then check if it's NaN:
$('input').on('keyup', function () {
var check_nm = +this.value;
console.log(isNaN(check_nm) ? 'not number' : 'is number');
});
Note whitespaces and empty string will be converted to 0, so they will be considered a number. If you don't want that, see https://stackoverflow.com/a/1830844/1529630.
Use jQuery's $.isNumeric().
Docs # jquery.com and cool discussion # SO

Dynamic insertion is not working in regular expression [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 9 years ago.
I have this function
function validateUsername(str,minL,maxL){// i'm passing validateUsername("asdf_1",2,8)
var exp=new RegExp(/^[a-z0-9_-]\w{"+minL+","+maxL+"}$/);
switch(exp.test(str)){
case true: return true;
case false: return false;
}
}
I want to insert minimum Length and maximum length dynamically,
But if above code used,its giving me false whether it should accept the string as true.
can anyone tell me, what should i use rather "+variable+" to insert the value dynamically.
Thanks in advance.
You can use the regex object constructor to build your regex from a string as stated here.
Example taken from linked answer :
var re = new RegExp("a|b", "i");
// same as
var re = /a|b/i;
In your case that would do something like :
function validateUsername(str,minL,maxL){// i'm passing validateUsername("asdf_1",2,8)
var exp=new RegExp("^[a-z0-9_-]\w{" + minL + "," + maxL + "}$");
/*
why ???
switch(exp.test(str)){
case true: return true;
case false: return false;
}
*/
return exp.test(str);
}
You can separate length validation from the pattern, something like this
if(str.length<minL || str.length>maxL){
// invalid length
}else{
var exp=new RegExp(/^[a-z0-9_-]\w$/);
return exp.test(str)
}

jQuery has/ contains words [duplicate]

This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 9 years ago.
I'd like to achieve that, if "clientpsseabq" string is contained in variable Var_words then equal true, else false. I just have no idea what method or function do I need to use?
var Var_words = "https://www.go.me/outputsearchs/clientpsseabq"
if ( Var_words contains string "`clientpsseabq`"){
return true;
}else{
return false;
}
if someone could help me how can I complete this task?
Use the (native JavaScript) function String.indexOf():
if(Var_words.indexOf('clientpsseabq') !== -1) {
return true;
} else {
return false;
}
.indexOf() returns the index of the string. If the string is not found, it returns -1.
A smaller, cleaner solution would be to simply return the value of the conditional directly:
return (Var_words.indexOf('clientpsseabq') !== -1);
You can try this
if (Var_words.indexOf("clientpsseabq") >= 0)
or with care of case sensitivity
if (Var_words.toLowerCase().indexOf("clientpsseabq") >= 0)
{
// your code
}
use a regular expression to test for the case
if(/clientpsseabq/.test(Var_words)){
//given string exists
} else {
//given string does not exists
}
if(Var_words.indexOf("clientpsseabq") >= 0))
{
}

Categories

Resources