我有两个类似这样的字段:
标题上的最后一个单词前没有空格。另一个有空格,因此这两个标题不视为相同的标题。
在我的应用中,我想说it's the same titles
后面有空格还是没有空格。
请问我该怎么做?
答案 0 :(得分:3)
您可以使用String.prototype.trim()
:
const title1 = "DisneyLand-Paris";
const title2 = "DisneyLand-Paris ";
const trimmed = title2.trim();
console.log(title1 === title2); // false
console.log(title1 === trimmed); // true
所以您可以这样做:
// Trim and compare both strings, and report the result.
function compareTitles(title1, title2) {
if (title1.trim() === title2.trim()) {
console.log("It's the same titles!");
}
}
compareTitles("DisneyLand-Paris", "DisneyLand-Paris "); // It's the same titles!
compareTitles("DisneyLand-Paris ", "DisneyLand-Paris"); // It's the same titles!
答案 1 :(得分:0)
您需要使用trim()方法
const string1 = "DisneyLand-Paris";
const string2 = "DisneyLand-Paris ";
const string3 = "";
if(string1 === string2.trim()){
string3 = `it's the same titles ` ; //here you have to use template literals because of it’s
console.log(string3);
}