How would I check whether a string contains the √ symbol?
var string = '√ foobar'
if (string.indexOf("f") > -1) { alert(string); }
Searching for "f", this finds the "f" in "foobar" fine. For what it's worth, the √ character does show as √ in the alert though:
var string = '√ foobar'
if (string.indexOf("√") > -1) { alert(string); }
Searching for "√" doesn't do anything, no alert message.
It works for me
var string = '√ foobar'
if (string.indexOf("√") > -1) {
alert(string);
}
But maybe the javascript environment which you are in, doesn't recognize the symbol, so I suggest you to try with the Unicode of that symbol. \u221A
var string = '√ foobar'
if (string.indexOf("\u221A") > -1) { alert(string); }
let example = '√ example';
console.log(example.includes('√'));
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
Related
I have created a JS fiddle https://jsfiddle.net/95r110s9/#&togetherjs=Emdw6ORNpc
HTML
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />
JS
validateinputentries(){
landlordstreetaddress2 = document.getElementById('landlordstreetaddress2').value;
goodcharacters = "/^[a-zA-Z0-9#.,;:'\s]+$/gi";
for (var i = 0; i < landlordstreetaddress2.length; i++){
if (goodcharacters.indexOf(landlordstreetaddress2.charAt(i)) != -1){
console.log('Character is valid');
}
}
}
Its pulling the value from an input and running an indexOf regex expression with A-Z a-z and 0-9 with a few additional characters as well.
The problem is that it works with the entry of BCDEFG...etc and 12345...etc, but when I type "A" or "Z" or "0" or "1", it returns incorrectly.
I need it to return the same with 0123456789, ABCDEF...XYZ and abcdef...xyz
I should point out that the below does work as intended:
var badcharacters = "*|,\":<>[]`\';#?=+/\\";
badcharacter = false;
//firstname
for (var i = 0; i < landlordfirstname.value.length; i++){
if (badcharacters.indexOf(landlordfirstname.value.charAt(i)) != -1){
badcharacter = true;
break;
}
if(landlordfirstname.value.charAt(0) == " "){
badcharacter = true;
break;
}
}
String.prototype.indexOf()
The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.
So, you're trying to search this value "/^[a-zA-Z0-9#.,;:'\s]+$/gi" which "never" will be found in the entered string.
You actually want to test that regexp against the entered value.
/^[a-zA-Z0-9#.,;:'\s]+$/gi.test(landlordstreetaddress2)
function validateinputentries() {
var landlordstreetaddress2 = document.getElementById('landlordstreetaddress2').value;
if (/^[a-zA-Z0-9#.,;:'\s]+$/gi.test(landlordstreetaddress2)) {
console.log('Characters are valid');
} else {
console.log('Characters are invalid');
}
}
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />
You're trying to combine two different methods of testing a string -- one way is with a regex; the other way is by checking each character against a list of allowed characters. What you've wound up with is checking each character against a list of what would have been a regex, if you hadn't declared it as a string.
Those methods conflict with each other; you need to pick one or the other.
Check each character:
This is closest to what you were attempting. You can't use character ranges here (like a-zA-Z) as you would in a regex; you have to spell out each allowed character individually:
var validateinputentries = function() {
var address = document.getElementById('landlordstreetaddress2').value;
var goodcharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#.,;:' ";
var badcharactersfound = false;
for (var i = 0; i < address.length; i++) {
if (goodcharacters.indexOf(address.charAt(i)) == -1) {
badcharactersfound = true;
console.log("not allowed: ", address.charAt(i));
}
}
if (badcharactersfound) {
// Show validation error here
}
}
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />
Regular Expressions
The regex version is much simpler, because the regular expression is doing most of the work. You don't need to step through the string, just test the whole string against the regex and see what comes out. In this case you're looking to see if the input contains any characters that aren't allowed, so you want to use the character exception rule: [^abc] will match any character that is not a, b, or c. You don't want to anchor the match to the beginning or the end of the string, as you were doing with the initial ^ and the trailing $; and you can leave out the + because you don't care if there are sequential bad characters, you just care if they exist at all.
var validateinputentries = function() {
var address = document.getElementById('landlordstreetaddress2').value;
var regex = new RegExp("[^a-zA-Z0-9#.,;:'\\s]","g")
var badcharactersfound = address.match(regex);
// or the above two lines could also have been written like this:
// var bad = address.match(/[^a-zA-Z0-9#.,;:'\s]/g)
// In either case the "g" operator could be omitted; then it would only return the first bad character.
if (badcharactersfound) {
console.log("Not allowed: ", badcharactersfound);
}
}
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />
How can i do to search if a Javascript String contains the following pattern :
"#aRandomString.temp"
I would like to know if the String contains # character and then any String and then ".temp" string.
Thanks
This one liner should do the job using regex#test(Strng):
var s = 'foo bar #aRandomString.temp baz';
found = /#.*?\.temp/i.test(s); // true
Use indexOf to find a string within a string.
var string = "#aRandomString.temp";
var apos = string.indexOf("#");
var dtemp = string.indexOf(".temp", apos); // apos as offset, invalid: ".temp #"
if (apos !== -1 && dtemp !== -1) {
var aRandomString = string.substr(apos + 1, dtemp - apos);
console.log(aRandomString); // "aRandomString"
}
You can try this
var str = "#something.temp";
if (str.match("^#") && str.match(".temp$")) {
}
demo
You can use the match function.
match expects the regular expression.
function myFunction()
{
var str="#someting.temp";
var n=str.test(/#[a-zA-Z]+\.temp/g);
}
Here is a demo: http://jsbin.com/IBACAB/1
I am looking for a function written in JavaScript (not in jQuery) which will return true if the given word exactly matches (should not be case sensitive).
Like...
var searchOnstring = " Hi, how are doing?"
if( searchText == 'ho'){
// Output: false
}
if( searchText == 'How'){
// Output: true
}
You could use regular expressions:
\bhow\b
Example:
/\bhow\b/i.test(searchOnstring);
If you want to have a variable word (e.g. from a user input), you have to pay attention to not include special RegExp characters.
You have to escape them, for example with the function provided in the MDN (scroll down a bit):
function escapeRegExp(string){
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
var regex = '\\b';
regex += escapeRegExp(yourDynamicString);
regex += '\\b';
new RegExp(regex, "i").test(searchOnstring);
Here is a function that returns true with searchText is contained within searchOnString, ignoring case:
function isMatch(searchOnString, searchText) {
searchText = searchText.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
return searchOnString.match(new RegExp("\\b"+searchText+"\\b", "i")) != null;
}
Update, as mentioned you should escape the input, I'm using the escape function from https://stackoverflow.com/a/3561711/241294.
Something like this will work:
if(/\show\s/i.test(searchOnstring)){
alert("Found how");
}
More on the test() method
Try this:
var s = 'string to check', ss= 'to';
if(s.indexOf(ss) != -1){
//output : true
}
This is my text string:
0000> hello world <0000
I want to count the characters between "0000>" and "<0000".
This will work:
s = "0000> hello my name is james, whats yours? <0000";
s.match(/0000>(.*?)<0000/)[1].length // returns 38;
But then again, so will this :-)
s.length - 10; // returns 38
This will do:
function count(string) {
var match = /0000>(.*)<0000/g.exec(string);
if (match.length > 1) {
return match[1].trim().length;
} else {
return null;
}
}
alert (count("0000> hello my name is james, whats yours? <0000"));
And the jsfiddle demo: http://jsfiddle.net/pSJGk/1/
Well, something like this would count everything (including spaces) between 0000> and <0000:
'0000> hello my name is james, whats yours? <0000'
.split(/0000>|<0000/g)[1].length; //=> 38
Or
'0000> hello my name is james, whats yours? <0000'
.replace(/0000>|<0000/g,'').length; //=> 38
function getLengthBetween(str,startStr,stopStr) {
var startPos = str.indexOf(startStr);
if(startPos == -1) {
return 0;
}
var startOffset = startPos+startStr.length;
var stopPos = str.indexOf(stopStr,startOffset);
if(stopPos == -1) {
stopPos = str.length;
}
return stopPos-startOffset;
}
Usage:
getLengthBetween("0000> hello my name is james, whats yours? <0000","0000>","<0000");
I'd suggest:
var str = " 0000> hello my name is james, whats yours? <0000",
start = "0000>",
end = "<0000",
between = str.substring(str.indexOf(start) + start.length, str.indexOf(end)).length;
console.log(between);
JS Fiddle demo.
This doesn't, however, trim the white-space from after the first match, or from before the second. This could be altered, of course, to match any given string delimiters by simply changing the variables.
References:
indexOf().
length.
substring().
I need to test for "[any number]" in a string in javascript. how would i match it?
Oh, "[" and "]" also need to be matched.
so string like "[1]" or "[12345]" is a match.
Non match: "[23432" or "1]"
So for example:
$('.form .section .parent').find('input.text').each(function(index){
$(this).attr("name", $(this).attr("name").replace("[current]", "['"+index+"']"));
});
I need to replace input fields name: "items[0].firstname" to "items[1].firstname"
thanks
UPDATE: for your updated question
variable.match(/\[[0-9]+\]/);
Try this:
variable.match(/[0-9]+/); // for unsigned integers
variable.match(/[-0-9]+/); // for signed integers
variable.match(/[-.0-9]+/); // for signed float numbers
if("123".search(/^\d+$/) >= 0){
// its a number
}
I always use the following regular expression to detect any kind of number in a string. Had no issues so far.
'(([\+\-]*\d*\.*\d+[eE])?([\+\-]*\d*\.*\d+))'
In detail:
'([\+\-]*\d*\.*\d+)'
to match a (non-)decimal number with(out) leading digits or sign
'([\+\-]*\d*\.*\d+[eE])?'
to match an exponential base before the number.
If there are brackets around required, you can add them inside or outside of the surrounding paranthesis:
'(\[([\+\-]*\d*\.*\d+[eE])?([\+\-]*\d*\.*\d+)\])'
In fact the surrounding paranthesis are not necessary, but i keep them to easier concatenate the expression with others.
var mask = /^\d+$/;
if ( myString.exec(mask) ){
/* That's a number */
}
You can use the following function to find the biggest [number] in any string.
It returns the value of the biggest [number] as an Integer.
var biggestNumber = function(str) {
var pattern = /\[([0-9]+)\]/g, match, biggest = 0;
while ((match = pattern.exec(str)) !== null) {
if (match.index === pattern.lastIndex) {
pattern.lastIndex++;
}
match[1] = parseInt(match[1]);
if(biggest < match[1]) {
biggest = match[1];
}
}
return biggest;
}
DEMO
The following demo calculates the biggest number in your textarea every time you click the button.
It allows you to play around with the textarea and re-test the function with a different text.
var biggestNumber = function(str) {
var pattern = /\[([0-9]+)\]/g, match, biggest = 0;
while ((match = pattern.exec(str)) !== null) {
if (match.index === pattern.lastIndex) {
pattern.lastIndex++;
}
match[1] = parseInt(match[1]);
if(biggest < match[1]) {
biggest = match[1];
}
}
return biggest;
}
document.getElementById("myButton").addEventListener("click", function() {
alert(biggestNumber(document.getElementById("myTextArea").value));
});
<div>
<textarea rows="6" cols="50" id="myTextArea">
this is a test [1] also this [2] is a test
and again [18] this is a test.
items[14].items[29].firstname too is a test!
items[4].firstname too is a test!
</textarea>
</div>
<div>
<button id="myButton">Try me</button>
</div>
See also this Fiddle!