startswith in javascript error - javascript

I'm using startswith reg exp in Javascript
if ((words).match("^" + string))
but if I enter the characters like , ] [ \ /, Javascript throws an exception.
Any idea?

If you're matching using a regular expression you must make sure you pass a valid Regular Expression to match(). Check the list of special characters to make sure you don't pass an invalid regular expression. The following characters should always be escaped (place a \ before it): [\^$.|?*+()
A better solution would be to use substr() like this:
if( str === words.substr( 0, str.length ) ) {
// match
}
or a solution using indexOf is a (which looks a bit cleaner):
if( 0 === words.indexOf( str ) ) {
// match
}
next you can add a startsWith() method to the string prototype that includes any of the above two solutions to make usage more readable:
String.prototype.startsWith = function(str) {
return ( str === this.substr( 0, str.length ) );
}
When added to the prototype you can use it like this:
words.startsWith( "word" );

One could also use indexOf to determine if the string begins with a fixed value:
str.indexOf(prefix) === 0

If you want to check if a string starts with a fixed value, you could also use substr:
words.substr(0, string.length) === string

If you really want to use regex you have to escape special characters in your string. PHP has a function for it but I don't know any for JavaScript. Try using following function that I found from [Snipplr][1]
function escapeRegEx(str)
{
var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
return str.replace(specials, "\\$&");
}
and use as
var mystring="Some text";
mystring=escapeRegEx(mystring);
If you only need to find strings starting with another string try following
String.prototype.startsWith=function(string) {
return this.indexOf(string) === 0;
}
and use as
var mystring="Some text";
alert(mystring.startsWith("Some"));

Related

Javascript regex to replace "split"

I would like to use Javascript Regex instead of split.
Here is the example string:
var str = "123:foo";
The current method calls:
str.split(":")[1]
This will return "foo", but it raises an Error when given a bad string that doesn't have a :.
So this would raise an error:
var str = "fooblah";
In the case of "fooblah" I'd like to just return an empty string.
This should be pretty simple, but went looking for it, and couldn't figure it out. Thank you in advance.
Remove the part up to and including the colon (or the end of the string, if there's no colon):
"123:foo".replace(/.*?(:|$)/, '') // "foo"
"foobar" .replace(/.*?(:|$)/, '') // ""
How this regexp works:
.* Grab everything
? non-greedily
( until we come to
: a colon
| or
$ the end of the string
)
A regex won't help you. Your error likely arises from trying to use undefined later. Instead, check the length of the split first.
var arr = str.split(':');
if (arr.length < 2) {
// Do something to handle a bad string
} else {
var match = arr[1];
...
}
Here's what I've always used, with different variations; this is just a simple version of it:
function split(str, d) {
var op = "";
if(str.indexOf(d) > 0) {
op = str.split(d);
}
return(op);
}
Fairly simple, either returns an array or an empty string.
var str1 = "123:foo", str2 = "fooblah";
var res = function (s) {
return /:/.test(s) && s.replace(/.*(?=:):/, "") || ""
};
console.log(res(str1), res(str2))
Here is a solution using a single regex, with the part you want in the capturing group:
^[^:]*:([^:]+)

Split string in JavaScript using regex with zero width lookbehind

I know JavaScript regular expressions have native lookaheads but not lookbehinds.
I want to split a string at points either beginning with any member of one set of characters or ending with any member of another set of characters.
Split before ເ, ແ, ໂ, ໃ, ໄ. Split after ະ.
In: ເລື້ອຍໆມະຫັດສະຈັນເອກອັກຄະລັດຖະທູດ
Out: ເລື້ອຍໆມະ ຫັດສະ ຈັນ ເອກອັກຄະ ລັດຖະ ທູດ
I can achieve the "split before" part using zero-width lookahead:
'ເລື້ອຍໆມະຫັດສະຈັນເອກອັກຄະລັດຖະທູດ'.split(/(?=[ໃໄໂເແ])/)
["ເລື້ອຍໆມະຫັດສະຈັນ", "ເອກອັກຄະລັດຖະທູດ"]
But I can't think of a general approach to simulating zero-width lookbehind
I'm splitting strings of arbitrary Unicode text so don't want to substitute in special markers in a first pass, since I can't guarantee the absence of any string from my input.
Instead of spliting, you may consider using the match() method.
var s = 'ເລື້ອຍໆມະຫັດສະຈັນເອກອັກຄະລັດຖະທູດ',
r = s.match(/(?:(?!ະ).)+?(?:ະ|(?=[ໃໄໂເແ]|$))/g);
console.log(r); //=> [ 'ເລື້ອຍໆມະ', 'ຫັດສະ', 'ຈັນ', 'ເອກອັກຄະ', 'ລັດຖະ', 'ທູດ' ]
You could try matching rather than splitting,
> var re = /((?:(?!ະ).)+(?:ະ|$))/g;
undefined
> var str = "ເລື້ອຍໆມະຫັດສະຈັນເອກອັກຄະລັດຖະທູດ"
undefined
> var m;
undefined
> while ((m = re.exec(str)) != null) {
... console.log(m[1]);
... }
ເລື້ອຍໆມະ
ຫັດສະ
ຈັນເອກອັກຄະ
ລັດຖະ
ທູດ
Then again split the elements in the array using lookahead.
If you use parentheses in the delimited regex, the captured text is included in the returned array. So you can just split on /(ະ)/ and then concatenate each of the odd members of the resulting array to the preceding even member. Example:
"ເລື້ອຍໆມະຫັດສະຈັນເອກອັກຄະລັດຖະທູ".split(/(ະ)/).reduce(function(arr,str,index) {
if (index%2 == 0) {
arr.push(str);
} else {
arr[arr.length-1] += str
};
return arr;
},[])
Result: ["ເລື້ອຍໆມະ", "ຫັດສະ", "ຈັນເອກອັກຄະ", "ລັດຖະ", "ທູ"]
You can do another pass to split on the lookahead:
"ເລື້ອຍໆມະຫັດສະຈັນເອກອັກຄະລັດຖະທູ".split(/(ະ)/).reduce(function(arr,str,index) {
if (index%2 == 0) {
arr.push(str);
} else {
arr[arr.length-1] += str
};
return arr;
},[]).reduce(function(arr,str){return arr.concat(str.split(/(?=[ໃໄໂເແ])/));},[]);
Result: ["ເລື້ອຍໆມະ", "ຫັດສະ", "ຈັນ", "ເອກອັກຄະ", "ລັດຖະ", "ທູ"]

Is there a python strip function equivalent in javascript?

Python's strip function is used to remove given characters from the beginning and end of the string. How to create a similar function in javascript?
Example:
str = "'^$ *# smart kitty & ''^$* '^";
newStr = str.strip(" '^$*#&");
console.log(newStr);
Output:
smart kitty
There's lodash's trim()
Removes leading and trailing whitespace or specified characters from string.
_.trim(' abc '); // → 'abc'
_.trim('-_-abc-_-', '_-'); // → 'abc'
A simple but not very effective way would be to look for the characters and remove them:
function strip(str, remove) {
while (str.length > 0 && remove.indexOf(str.charAt(0)) != -1) {
str = str.substr(1);
}
while (str.length > 0 && remove.indexOf(str.charAt(str.length - 1)) != -1) {
str = str.substr(0, str.length - 1);
}
return str;
}
A more effective, but not as easy to use, would be a regular expression:
str = str.replace(/(^[ '\^\$\*#&]+)|([ '\^\$\*#&]+$)/g, '')
Note: I escaped all characters that have any special meaning in a regular expression. You need to do that for some characters, but perhaps not all the ones that I escaped here as they are used inside a set. That's mostly to point out that some characters do need escaping.
Modifying a code snippet from Mozilla Developer Network String.prototype.trim(), you could define such a function as follows.
if (!String.prototype.strip) {
String.prototype.strip = function (string) {
var escaped = string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
return this.replace(RegExp("^[" + escaped + "]+|[" + escaped + "]+$", "gm"), '');
};
}
It's not necessary and probably not advisable to put this function in the object String.prototype, but it does give you a clear indication of how such a function compares with the existing String.prototype.trim().
The value of escaped is as in the function escapeRegExp in the guide to Regular Expressions. The Java programming language has a standard library function for that purpose, but JavaScript does not.
Not exactly... I would use regex for complicated string manipulation or the Slice() method to remove characters at certain points
Slice() explained

jQuery - check whether string contains numeric value

How to check whether a string contains any numeric value by jquery?
I search through many examples but I only get the way to check for a number, NOT number in a STRING. I am trying to find something like $(this).attr('id').contains("number");
(p/s: my DOM id will be something like Large_a (without numeric value) , Large_a_1 (with numeric value), Large_a_2, etc.)
What method should I use?
You could use a regular expression:
var matches = this.id.match(/\d+/g);
if (matches != null) {
// the id attribute contains a digit
var number = matches[0];
}
This code detects trailing digits preceded by the underscore symbol (azerty1_2 would match "2", but azerty1 would not match):
if (matches = this.id.match(/_(\d)+$/))
{
alert(matches[1]);
}
Simple version:
function hasNumber(s) {
return /\d/.test(s);
}
More efficient version (keep regular expression in a closure):
var hasNumber = (function() {
var re = /\d/;
return function(s) {
return re.test(s);
}
}());

preg_match to Javascript function

$value = 077283331111333;
if( ! preg_match(/^[0-9]{1,20}+$/, $value))
{
echo $value . " is not a number that has between 1,20 digits";
}
I'm trying to turn this Php conditional statement into a Javascript one.
This is what I have, currently not working.
var value = 077283331111333;
var regex = '/^[0-9]{1,20}+$/';
var match = regex.test(value);
if ( ! match) {
console.log(value + 'is not a number that has between 1,20 digits');
}
And this is the error I'm getting.
Object /^[1,0]{1}+$//^[0-9]{1,20}+$/ has no method 'test'
Any ideas? Additionally this within a node.js environment.
That method is undefined because that's not a regex but a string.
You need to drop the quotes in order to create a RegExp object in javascript:
var regex = /^[1,0]{1}+$//^[0-9]{1,20}+$/;
Anyway I don't think that's a valid regex (because of the double slashes) you might wanna check for typos there...
A regex to check for a number between 1 and 20 digits is just:
var regex = /^\d{1,20}$/
try to remove single quotes from your regex
var value = 077283331111333;
var regex = /^[1,0]{1}+$//^[0-9]{1,20}+$/;
var match = regex.test(value);
if ( ! match) {
console.log(value + 'is not a number that has between 1,20 digits');
}
try remove the quotes from regex variable.
if ( /regex/.match( value ) ) {
//do stuff
}
That's one odd regexp... why don't you use
/^\d{1,20}$/.test(value)

Categories

Resources