2016-12-29 4 views
2

JavaScriptを使用してドメイン名の前後にあるhrefの値をトリミングしようとしています。たとえば、http://www.google.com/about-usは、www.google.comにトリムする必要があります。JavaScript IndexOfから部分文字列を作成できません

var str = "http://www.google.com/about-us"; 
 
var str_before = str.replace("http://",""); 
 
document.write(str_before); // Returns ("www.google.com/about-us") 
 

 
// Trim everything after the domain name 
 

 
var link = str_before.substring(0, str_before.indexOf('/')); 
 
document.write(link); // Returns "www.google.com/about-uswww.google.com"

なぜこれが起こっている私は知りません。どんな助けでも大歓迎です!

+0

'VAR A =のdocument.createElement( "A")。 a.href = str;ホスト; // "www.google.com" ' –

+1

いいえ、あなたを欺く' document.write'です。 'console.log'を使ってコードの結果を確認してください。 – Teemu

+2

document.writeを使用しないでください。存在しないことを忘れないでください。なぜ初心者コースは人々にそれを使用するように教えるのですが、もう90/00sではありません。 – epascarello

答えて

2

これまでのdocument.writeの出力は、2番目のdocument.writeの出力と連結されています。出力に改行を追加すると、実際の出力が2行で表示され、結果が実際に正しいことがわかります。

は、以下のコードを試してください:

var str = "http://www.google.com/about-us"; 
 
var str_before = str.replace("http://",""); 
 
document.write(str_before); // Outputs "www.google.com/about-us" 
 

 
// Trim everything after the domain name 
 
var link = str_before.substring(0, str_before.indexOf('/')); 
 

 
//add line break to the output 
 
document.write('<br />'); 
 

 
//output the resulting link 
 
document.write(link);

+0

ありがとう!私はその場所にあるdocument.write()行を見落としていました。 –

関連する問題