js比较变量和div文本
js compare between variable and div text
我正在尝试比较 div 中文本的值(这是一个句子。)和 js 变量中定义的文本:
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...");
}
}
所有 .replace 是因为在控制台上我在 div 中有额外的选项卡(其中有样式)我有额外的空格。控制台日志显示:
Thisisasentence. VS
Thisisasentence.
Not same...
我缺少什么?
您的正则表达式看起来像是在尝试替换任何空白字符。我建议使用 \s 作为正则表达式的一部分,因为它会查找空格的所有排列。
你的两个字符串不相等,因为短语前后有一个换行符。您可以尝试用 .replace('\n', '')
替换新行
您是否尝试过使用 trim()
方法而不是整个正则表达式?
如 documentation for String.prototype.trim() 中所述,在 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.).
我相信您的代码应该减少为:
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...");
}
}
并且比较会按预期工作。
更新:
正如 Ysharp and Rob Brander 在进一步回答中提到的那样,您可以通过将正则表达式扩展到其他匹配新行和回车 return 元素来增加正则表达式。这将通过向其添加 \s+
匹配器来更改您当前的正则表达式,从而导致:
replace(/\s+/g, '')
您尝试使用
去除空格
replace(/ /g, '')
但正如其他人指出的那样,这不足以摆脱运输 returns and/or 换行符。
试试这个:
replace(/\s+/g, '')
它将负责去除所有应用它的字符串中的所有 '\t'、'\n' 等。
'HTH,
我正在尝试比较 div 中文本的值(这是一个句子。)和 js 变量中定义的文本:
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...");
}
}
所有 .replace 是因为在控制台上我在 div 中有额外的选项卡(其中有样式)我有额外的空格。控制台日志显示:
Thisisasentence. VS
Thisisasentence.
Not same...
我缺少什么?
您的正则表达式看起来像是在尝试替换任何空白字符。我建议使用 \s 作为正则表达式的一部分,因为它会查找空格的所有排列。
你的两个字符串不相等,因为短语前后有一个换行符。您可以尝试用 .replace('\n', '')
替换新行您是否尝试过使用 trim()
方法而不是整个正则表达式?
如 documentation for String.prototype.trim() 中所述,在 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.).
我相信您的代码应该减少为:
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...");
}
}
并且比较会按预期工作。
更新:
正如 Ysharp and Rob Brander 在进一步回答中提到的那样,您可以通过将正则表达式扩展到其他匹配新行和回车 return 元素来增加正则表达式。这将通过向其添加 \s+
匹配器来更改您当前的正则表达式,从而导致:
replace(/\s+/g, '')
您尝试使用
去除空格replace(/ /g, '')
但正如其他人指出的那样,这不足以摆脱运输 returns and/or 换行符。
试试这个:
replace(/\s+/g, '')
它将负责去除所有应用它的字符串中的所有 '\t'、'\n' 等。
'HTH,