Reputation: 135
I'm trying to compare value of text inside div (This is a sentence.) and text defined in js variable:
function isSame(){
s="This is a sentence."
var text1 = $('#right').text();
var t1 = text1.replace(/ /g,'').replace(/ /g, '').replace(/\<br\s*[\/]?>/gi, '').replace('\t','');
var s1 = s.replace(/ /g,'').replace(/ /g, '').replace(/\<br\s*[\/]?>/gi, '').replace('\t','');
console.log(s1+" VS "+ t1);
if (t1 == s1){
console.log("Same");
} else {
console.log("Not same...");
}
}
All the .replace are because on console I had extra tabs in div (which has style in it) I had extra spaces. Console log shows:
Thisisasentence. VS
Thisisasentence.
Not same...
What is it I'm missing?
Upvotes: 0
Views: 209
Reputation: 1554
Instead of this entire regular expression, have you tried using the trim()
method?
As stated in the documentation for String.prototype.trim(), in MDN:
The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
I believe your code should then be reduced to:
function isSame() {
var s = "This is a sentence.";
var text1 = $('#right').text();
console.log(s1 + " VS " + t1);
if (text1.trim() === s1) {
console.log("Same");
} else {
console.log("Not the same...");
}
}
And the comparison would work as expected.
Update:
As already mentioned in further answers by Ysharp and Rob Brander, you could increment your regular expression by expanding it to other match new lines and carriage return elements. That would change your current regex by adding a \s+
matcher to it, resulting in:
replace(/\s+/g, '')
Upvotes: 2
Reputation: 1086
You tried to get rid of whitespace using
replace(/ /g, '')
but as others pointed out, this is not sufficient to get rid of carriage returns and/or newlines.
Try this instead:
replace(/\s+/g, '')
which will take care of stripping out all of the '\t', '\n', etc, everywhere in the strings it is applied to.
'HTH,
Upvotes: 0
Reputation: 3781
Your regular expressions look like they're trying to replace any whitespace characters. I would suggest using \s as part of your regular expression, because that looks for all permutations of whitespace.
Your two strings are not equal because there is a newline before and after the phrase. You could try replacing just the new lines with .replace('\n', '')
Upvotes: 0