The difference between "" vs " " Javascript - javascript

I used this to remove white spaces from a string.
returnString.split(" ").filter(substr => substr !== "");
In my head it should be this:
returnString.split(" ").filter(substr => substr !== " ") //note the space between the " "
why doesnt the bottom one work? Is it JS sytax?
Answer: If theres a space at the beginning of the string, its split with an empty string, (so substr !== "") removes that from the returned array when splitting the string.

returnString.replace(/\s/g,'') Would be a superior way of doing this.
"" is an empty string.
" " is a space character.
They cannot be used interchangeably.

"" is an empty string.
If there is a space at the beginning of the string, it will split that space with an empty string.
that is why substr !== "" is needed to remove the empty string.

As mentioned in the comments, you’re splitting on whitespaces, creating indices for said whitespaces in an array.
const returnString = 'Hello I am Victor'
const str = returnString.split("").filter(substr => substr !== " ");
console.log(str.join(''))
would get you the desired result.
However, a regex pattern would be best suited for this use case.
returnString.replace(/\s/g, '')

Related

How to check if a string contains a WORD in javascript? [duplicate]

This question already has answers here:
How to check if a string contain specific words?
(11 answers)
Closed 3 years ago.
So, you can easily check if a string contains a particular substring using the .includes() method.
I'm interested in finding if a string contains a word.
For example, if I apply a search for "on" for the string, "phones are good", it should return false. And, it should return true for "keep it on the table".
You first need to convert it into array using split() and then use includes()
string.split(" ").includes("on")
Just need to pass whitespace " " to split() to get all words
This is called a regex - regular expression
You can use of 101regex website when you need to work around them (it helps). Words with custom separators aswell.
function checkWord(word, str) {
const allowedSeparator = '\\\s,;"\'|';
const regex = new RegExp(
`(^.*[${allowedSeparator}]${word}$)|(^${word}[${allowedSeparator}].*)|(^${word}$)|(^.*[${allowedSeparator}]${word}[${allowedSeparator}].*$)`,
// Case insensitive
'i',
);
return regex.test(str);
}
[
'phones are good',
'keep it on the table',
'on',
'keep iton the table',
'keep it on',
'on the table',
'the,table,is,on,the,desk',
'the,table,is,on|the,desk',
'the,table,is|the,desk',
].forEach((x) => {
console.log(`Check: ${x} : ${checkWord('on', x)}`);
});
Explaination :
I am creating here multiple capturing groups for each possibily :
(^.*\son$) on is the last word
(^on\s.*) on is the first word
(^on$) on is the only word
(^.*\son\s.*$) on is an in-between word
\s means a space or a new line
const regex = /(^.*\son$)|(^on\s.*)|(^on$)|(^.*\son\s.*$)/i;
console.log(regex.test('phones are good'));
console.log(regex.test('keep it on the table'));
console.log(regex.test('on'));
console.log(regex.test('keep iton the table'));
console.log(regex.test('keep it on'));
console.log(regex.test('on the table'));
You can .split() your string by spaces (\s+) into an array, and then use .includes() to check if the array of strings has your word within it:
const hasWord = (str, word) =>
str.split(/\s+/).includes(word);
console.log(hasWord("phones are good", "on"));
console.log(hasWord("keep it on the table", "on"));
If you are worried about punctuation, you can remove it first using .replace() (as shown in this answer) and then split():
const hasWord = (str, word) =>
str.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"").split(/\s+/).includes(word);
console.log(hasWord("phones are good son!", "on"));
console.log(hasWord("keep it on, the table", "on"));
You can split and then try to find:
const str = 'keep it on the table';
const res = str.split(/[\s,\?\,\.!]+/).some(f=> f === 'on');
console.log(res);
In addition, some method is very efficient as it will return true if any predicate is true.
You can use .includes() and check for the word. To make sure it is a word and not part of another word, verify that the place you found it in is followed by a space, comma, period, etc and also has one of those before it.
A simple version could just be splitting on the whitespace and looking through the resulting array for the word:
"phones are good".split(" ").find(word => word === "on") // undefined
"keep it on the table".split(" ").find(word => word === "on") // "on"
This just splits by whitespace though, when you need parse text (depending on your input) you'll encounter more word delimiters than whitespace. In that case you could use a regex to account for these characters.
Something like:
"Phones are good, aren't they? They are. Yes!".split(/[\s,\?\,\.!]+/)
I would go with the following assumptions:
Words the start of a sentence always have a trailing space.
Words at the end of a sentence always have a preceding space.
Words in the middle of a sentence always have a trailing and preceding space.
Therefore, I would write my code as follows:
function containsWord(word, sentence) {
return (
sentence.startsWith(word.trim() + " ") ||
sentence.endsWith(" " + word.trim()) ||
sentence.includes(" " + word.trim() + " "));
}
console.log(containsWord("test", "This is a test of the containsWord function."));
Try the following -
var mainString = 'codehandbook'
var substr = /hand/
var found = substr.test(mainString)
if(found){
console.log('Substring found !!')
} else {
console.log('Substring not found !!')
}

Replace null bytes

I want to replace null bystes from string. But after replacing of the null bytes \u0000 of the string
let data = {"tet":HelloWorld.\u0000\u0000\u0000\u0000"}
let test = JSON.parse(data).tet.replace("\u0000", "");
I am getting always following value:
HelloWorld.[][][][]
This are not array brackets or something like that.
I just need the value HelloWorld. How can I do this?
Ok, the solution was to replace all bytes.
.replace(new RegExp("\u0000", "g"), "");
A normal string replace only replaces the first occurence.
But by using a regex with a global flag it'll replace all occurences.
Example snippet :
console.log("bar bar".replace("bar","foo"));
console.log("bar bar".replace(/bar/g,"foo"));
let data = {"test":"HelloWorld.\u0000\u0000\u0000\u0000"};
console.log("before: " + data.test);
console.log("before (stringified): " + JSON.stringify(data.test));
// removing all the NULL unicode characters
data.test = data.test.replace(/\u0000/g,'');
console.log("after (stringified): " + JSON.stringify(data.test));

Javascript replace regex any character

I am trying to replace something like '?order=height' and I know it can be easily done like this:
data = 'height'
x = '?order=' + data
x.replace('?order=' + data, '')
But the problem is that question mark can sometimes be ampersand.. What I really wish to do is make blank whether the first character is ampersand or question mark so basically whether
?order=height
&order=height
can be made a blank string
x.replace(/[&?]order=height/, '')
If data is string variable
x.replace(/[&?]order=([^&=]+)/, '')
Use regex for that .replace(/[?&]order=height/, '')
[?&] means any character from this list.
/ is start and end delimiter.
Please note that pattern is not enclosed as string with ' or ".
This is how you may do it. Create a RegExp object with
"[&?]order=" + match
and replace with "" using String.prototype.replace
function replace(match, str) {
regex = new RegExp("[&?]order=" + match,"g")
return str.replace(regex, "")
}
console.log(replace("height", "Yo &order=height Yo"))
console.log(replace("weight", "Yo ?order=weight Yo"))
console.log(replace("age", "Yo ?order=age Yo"))

Two equal strings representing whitespaces not equals in JS

I am encountering a problem trying to replace whitespaces in a number.
For instance, this works, i.e. it returns 27721 as expected:
alert("27 721".replace(/ /g, ""));
While - I don't know why - this does not (my browser is in french so thousand separator is a whitespace) :
function getThousandSeparator() {
var testN = 1000;
return testN.toLocaleString().replace(/\d/g,"");
}
alert("27 721".replace(new RegExp(getThousandSeparator(), "g"), ""));
And if I make the function directly return " " then it works.
Also, if you test :
console.log(getThousandSeparator() == " ");
it shows false...
Thank you in advance.
In my testing, the separator character is actually an (non-breaking space), not a real space.

How to detect string which contains only spaces?

A string length which contains one space is always equal to 1:
alert('My str length: ' + str.length);
The space is a character, so:
str = " ";
alert('My str length:' + str.length); // My str length: 3
How can I make a distinction between an empty string and a string which contains only spaces? How can I detect a string which contain only spaces?
To achieve this you can use a Regular Expression to remove all the whitespace in the string. If the length of the resulting string is 0, then you can be sure the original only contained whitespace. Try this:
var str = " ";
if (!str.replace(/\s/g, '').length) {
console.log('string only contains whitespace (ie. spaces, tabs or line breaks)');
}
The fastest solution would be using the regex prototype function test() and looking for any character that is not a space, tab, or line break \S :
if (!/\S/.test(str)) {
// Didn't find something other than a space which means it's empty
}
In case you have a super long string, it can make a significant difference as it will stop processing as soon as it finds a non-space character.
Similar to Rory's answer, with ECMA 5 you can now just call str.trim().length instead of using a regular expression. If the resulting value is 0 you know you have a string that contains only spaces.
if (!str.trim().length) {
console.log('str is empty!');
}
You can read more about trim here.
Edit: After looking at this a few years later I noticed this could be simplified further. Since the result of trim will either be truthy or falsy you can also do the following:
if (!str.trim()) {
console.log('str is empty!');
}
if(!str.trim()){
console.log('string is empty or only contains spaces');
}
String#trim() removes the whitespace at the start and end of the string. If the string contained only whitespace, it would be empty after trimming, and the empty string is falsey in JavaScript.
If the string might be null or undefined, we need to first check if the string itself is falsey before trimming.
if(!str || !str.trim()){
//str is null, undefined, or contains only spaces
}
This can be simplified using the optional chaining operator.
if(!str?.trim()){
//str is null, undefined, or contains only spaces
}
You can Trim your String value by creating a trim function for your Strings.
String.prototype.trim = function () {
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
now it will be available for your every String and you can use it as
str.trim().length// Result will be 0
You can also use this method to remove the white spaces at the start and end of the String i.e
" hello ".trim(); // Result will be "hello"
You can do this by simply using trim.
var str = " ";
if (str.trim().length == 0)
{
console.log("Your string contains only white spaces.")
}
Trim your String value by creating a trim function
var text = " ";
if($.trim(text.length == 0){
console.log("Text is empty");
}
else
{
console.log("Text is not empty");
}
If we want to check if string contains only white spaces, then this might be helpful.
const str = ' ';
console.log(/^\s+$/.test(str));
This will log true.
Typecasting to Number can detect whitespace-only strings (if strings containing only zeros can be excluded):
if (+' ' === 0) console.log('is whitespace');
to make this approach also work for empty- and zerostrings like '0' a truthy numerical prefix could be used:
if (Number('1 0') === 1) console.log('is not whitespace');
if (Number('1 ' + ' \n ') === 1) console.log('is whitespace');
but concatenated casting is expensive - leading to this obscure expression:
String(x || '').indexOf('0') < +x
however, performance- and readability wise - trimed-length still wins over regex or casting-magic.
const tests = ['',' ', '\t\n\r','0',' 0 ','x',' 404 '];
tests.filter(x => String(x || '').trim().length === 0); // fastest
tests.filter(x => /^\s*$/.test(x)); // 33% slower
tests.filter(x => +x === 0 && String(x).indexOf('0') === -1); // 40 % slower
tests.filter(x => String(x || '').indexOf('0') < +x); // 50% slower
tests.filter(x => Number('1 ' + x) === 1); // 66% slower
This works in Dart not Javascript. However, when I searched up how to do this with Dart this question came up, so I figured others may need the Dart answer.
String foo = ' ';
if (foo.replaceAll(' ', '').length == 0) {
print('ALL WHITE SPACE');
}
else {
print('NOT ALL WHITE SPACE');
}
To further clarify, the String ' d ' will print 'NOT ALL WHITE SPACE' and the String ' ' will print 'ALL WHITE SPACE'.

Categories

Resources