2013-06-21 45 views
2

我想寫一個使用jQuery的功能文本()替換字符串我怎麼用jQuery剝離HTML功能

想這裏面的html函數內部:

function formatData(inputstring) { 

    // strip HTML 
    var output = $(inputstring).text(); 

    // ... do some more stuff with output 

    return output ; 
} 

,然後用它就像

alert (formatData("some <b>html</b> stuff")) 

爲什麼這不起作用?

+0

什麼是輸入這裏 – PSR

+0

你怎麼稱呼呢?輸入應該是一個有效的jQuery選擇器。 – BigMike

+0

輸入應該是一個字符串 – rubo77

回答

4

請確保該字符串是一個有效的jQuery對象,然後從它得到text(),我正在製作一個函數,因爲它是你所要求的,但是如果你不多次調用它,它可以內聯。

function removeHtml(input){ 
    return $("<span>"+input+"</span>").text(); 
} 

alert(removeHtml("I was a string with <h1>HTML!</h1>")); 

Demo

+0

謝謝,那工作!奇怪的是,它也有一個缺失>在末端跨度) – rubo77

+0

@ rubo77雖然它的工作(這是一個錯字),你應該關閉它:) –

+0

我補充一點:'input = input.replace(「
」, 「」);'那麼像'some
words'這樣的東西顯示正確(也許類似於'
')。我在這裏使用它:https://github.com/rubo77/TableCSVExport/blob/9510563234eba1595a2c6de4b0420456d79f5f2e/jquery.TableCSVExport.js#L141 – rubo77

1

我想你從一個表單輸入/ textarea的字段輸入值。 嘗試做這樣的事情:

var output = $('<div>' + input + '</div>').text();