in a javascript if...else statement, instead of checking if a variable equals (==) a value, is it possible to check if a variable includes a value?
var blah = unicorns are pretty;
if(blah == 'unicorns') {}; //instead of doing this,
if(blah includes 'unicorns') {}; //can i do this?
also, the word it includes should be the FIRST word of the variable. Thanks!!!
If by "first word", you mean a character sequence from the beginning of the string to the first space, then this will do it:
if ((sentence + ' ').indexOf('unicorns ') === 0) {
// note the trailing space ^
}
If instead of a space it can be any white-space character, you should use a regular expression:
if (/^unicorns(\s|$)/.test(sentence)) {
// ...
}
// or dynamically
var search = 'unicorns';
if (RegExp('^' + search + '(\\s|$)').test(sentence)) {
// ...
}
You can also use the special word-boundary character, depending on the language you want to match:
if (/^unicorns\b/.test(sentence)) {
// ...
}
More about regular expressions.
Related question:
How to check if a string "StartsWith" another string?
if(blah.indexOf('unicorns') == 0) {
// the string "unicorns" was first in the string referenced by blah.
}
if(blah.indexOf('unicorns') > -1) {
// the string "unicorns" was found in the string referenced by blah.
}
indexOf
To remove the first occurrence of a string:
blah = blah.replace('unicorns', '');
You can also use a quick regex test:
if (/unicorns/.test(blah)) {
// has "unicorns"
}
Related
I am trying to make ifcondition for a large number of chars.
I can use
if (str==!||str==#||str==#||str==$||str==^||str==&)
And so on, but this seems very inefficient. I would like to get the condition to work if the char is on of those:
!##%$^&()_-+=\?/.,'][{}<>`~
Is there is any shorter and more efficient way of doing it?
for (var c0 = 1; c0 > fn.length++; c0++) {
var str = fn.charAt(c0--);
if (str ==-"!##%$^&()_-+=\?/.,'][{}<>`~") {
}
}
I want the check to accrue on every single char from the string above.
You can use a regular expression character class to check if your character matches a particular character:
/^[\!##%$\^&\(\)_\-\+=\?\/\.,'\]\[\{\}\<\>`~]$/
Here I have escape special characters so that they get treated like regular characters.
See working example below:
const regex = /^[\!##%$\^&\(\)_\-\+=\?\/\.,'\]\[\{\}\<\>`~]$/,
charA = '#', // appears in char set
charB = 'A'; // doesn't appear in char set
console.log(regex.test(charA)); // true
console.log(regex.test(charB)); // false
Alternatively, if you don't want to use regular expressions you can instead put all your characters into an array and use .includes to check if your character is in your array.
const chars = "!##%$^&()_-+=\?/.,'][{}<>`~",
charArr = [...chars],
charA = '#', // is in char set
charB = 'A'; // isn't in char set
console.log(charArr.includes(charA)); // true
console.log(charArr.includes(charB)); // false
Just use regular expressions rather than manual single character checking.
const pattern = new RegExp("!##%$^&()_-+=\?\/.,'][{}<>`~");
const exists = pattern.test(str);
if (exists) {
// code logic for special character exists in string
}
First you can use split('') to split a string into an array of characters. Next you can use .some to check if a condition is true for at least one element in the array:
"!##%$^&()_-+=\?/.,'][{}<>`~".split('').some(x => x === str)
Is there a way to compare a string against a string containing escape characters.
What I have to far is:
var text = '\\SPX\FTP';
if(text.substring(0,2) === '\\'){
console.info('true')
}
This should be true but isn't.
As one of the \ is escaped, you need to compare to one character only:
var text = '\\SPX\FTP';
if(text.substring(0,1) === '\\'){
console.info('true')
}
If you have access to tagged template strings in ES6, or are transpiling using Babel, you can use String.raw:
var text = String.raw`\\SPX\FTP`;
if(text.substring(0,2) === String.raw`\\`){
console.info('true')
}
Returns true.
Either compare to one character or two, depending on what you require.
One (I suspect this is the one you'll need):
var text = '\\SPX\FTP';
if (text.substring(0, 1) === '\\') { // Remember \\ after escape == \
console.info('true')
}
Two:
var text = '\\SPX\FTP';
if (text.substring(0, 2) === '\\S') {
console.info('true')
}
var input = [paul, Paula, george];
var newReg = \paula?\i
for(var text in input) {
if (newReg.test(text) == true) {
input[input.indexOf(text)] = george
}
}
console.log(input)
I don't know what's wrong in my code. it should change paul and Paula to george but when I run it it says there's an illegal character
The backslash (\) is an escape character in Javascript (along with a lot of other C-like languages). This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n is a newline character (rather than a backslash followed by the letter n).
So, thats what is causing your error, you need to replace \paula?\i with /paula?/i
You need to replace \ by / in your regexp pattern.
You should wrap the strings inside quotes "
You need to match correctly your array, val is just the index of the word, not the word himself.
var input = ["paul", "Paula", "george"];
var newReg = /paula?/i;
for (var val in input) {
if (newReg.test(input[val]) == true) {
input[input.indexOf(input[val])] = "george";
}
}
console.log(input);
JSFIDDLE
I'm using an ES6-like variable formatting with the syntax of ${varName}, and while processing them I'm trying to enumerate all unique variables specified, using the following code:
function enumVars(txt) {
var v, names = [];
var reg = /\$\{\s*[a-zA-Z\$_][a-zA-Z0-9\$_]*\s*}/g;
while (v = reg.exec(txt)) {
var svn = v[0].replace(/???/, ''); // stripped variable name;
if (names.indexOf(svn) === -1) {
names.push(svn);
}
}
return names;
}
I haven't been able to figure out the correct RegExp for stripping the variable name from the exec result.
When I use v[0], it gives me ${varName} string, and I need to strip it into just varName, removing leading ${, trailing }, and all white spaces that may reside inside { } around the variable.
The variable is expected to follow the javascript naming convention, which means:
a valid variable starts with a letter, underscore or '$' symbol, followed by any combination of letters, digits, underscores or '$';
leading and trailing spaces around the variable are to be ignored.
In all, we may have a variable returned from exec as ${ _$abc12_$ }, and I need a RegExp for calling replace that would return just _$abc12_$.
Thanks everyone for helping!
Your replace regexp could be
/^\$\{\s*|\s*}$/g
In English, this says "remove both ${... at the beginning, or ...} at the end.
It could be slightly easier to just grab all the strings, and transform them all at once, then filter out duplicates:
function enumVars(txt) {
return txt
// Find all matches of form ${var}
. match(/\$\{\s*[a-z$_][a-z0-9$_]*\s*}/gi)
// Strip off ${ and }, yielding just variable name
. map(function(v) { return v.replace( /^\$\{\s*|\s*}$/g, ''); })
// Filter out duplicates
. filter(function(v, i, a) { return a.indexOf(v) === i; });
}
The replace function returns the new string with the replaces, but if there weren't any words to replace, then the original string is returned. Is there a way to know whether it actually replaced anything apart from comparing the result with the original string?
A simple option is to check for matches before you replace:
var regex = /i/g;
var newStr = str;
var replaced = str.search(regex) >= 0;
if(replaced){
newStr = newStr.replace(regex, '!');
}
If you don't want that either, you can abuse the replace callback to achieve that in a single pass:
var replaced = false;
var newStr = str.replace(/i/g, function(token){replaced = true; return '!';});
As a workaround you can implement your own callback function that will set a flag and do the replacement. The replacement argument of replace can accept functions.
Comparing the before and after strings is the easiest way to check if it did anything, there's no intrinsic support in String.replace().
[contrived example of how '==' might fail deleted because it was wrong]
Javascript replace is defected by design. Why? It has no compatibility with string replacement in callback.
For example:
"ab".replace(/(a)(b)/, "$1$2")
> "ab"
We want to verify that replace is done in single pass. I was imagine something like:
"ab".replace(/(a)(b)/, "$1$2", function replacing() { console.log('ok'); })
> "ab"
Real variant:
"ab".replace(/(a)(b)/, function replacing() {
console.log('ok');
return "$1$2";
})
> ok
> "$1$2"
But function replacing is designed to receive $0, $1, $2, offset, string and we have to fight with replacement "$1$2". The solution is:
"ab".replace(/(a)(b)/, function replacing() {
console.log('ok');
// arguments are $0, $1, ..., offset, string
return Array.from(arguments).slice(1, -2)
.reduce(function (pattern, match, index) {
// '$1' from strings like '$11 $12' shouldn't be replaced.
return pattern.replace(
new RegExp("\\$" + (index + 1) + "(?=[^\\d]|$)", "g"),
match
);
}, "$1$2");
});
> ok
> "ab"
This solution is not perfect. String replacement itself has its own WATs. For example:
"a".replace(/(a)/, "$01")
> "a"
"a".replace(/(a)/, "$001")
> "$001"
If you want to care about compatibility you have to read spec and implement all its craziness.
If your replace has a different length from the searched text, you can check the length of the string before and after. I know, this is a partial response, valid only on a subset of the problem.
OR
You can do a search. If the search is successfull you do a replace on the substring starting with the found index and then recompose the string. This could be slower because you are generating 3 strings instead of 2.
var test = "Hellllo";
var index = test.search(/ll/);
if (index >= 0) {
test = test.substr(0, index - 1) + test.substr(index).replace(/ll/g, "tt");
}
alert(test);
While this will require multiple operations, using .test() may suffice:
const regex = /foo/;
const yourString = 'foo bar';
if (regex.test(yourString)) {
console.log('yourString contains regex');
// Go ahead and do whatever else you'd like.
}
The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.
With indexOf you can check wether a string contains another string.
Seems like you might want to use that.
have a look at string.match() or string.search()
After doing any RegExp method, read RegExp.lastMatch property:
/^$/.test(''); //Clear RegExp.lastMatch first, Its value will be ''
'abcd'.replace(/bc/,'12');
if(RegExp.lastMatch !== '')
console.log('has been replaced');
else
console.log('not replaced');