2016-12-12 6 views
0

こんにちは、このようなjavascriptの文字列ソリューションを置き換えたいと思います。JavaScriptを<title>に置き換えます。<span>タイトル</span>

input:- this is <title> and <heading> 
output:- this is <span>title</span> and <span>heading</span> 

誰でも私にこれを助けることができます。 ありがとうございます。 1つの以上の非>文字が続く、開口部<と一致し、ある

var input = "this is <title> and <heading>"; 
 
var output = input.replace(/<([^>]+)>/g, "<span>$1</span>"); 
 
console.log(output);

:このような何かを試してみてください

input.replace(/</g, '<span_').replace(/>/g,'</span>').replace(/_/g,'>'); 
+0

あなたはJSを経由して、それを達成したいですか? –

+0

文字列を解析する必要がありますタイトルの使用を検索する必要があります 'includes' –

答えて

1

を交換する

+0

を見出しタイトルとあるおかげで...それは –

2

使用正規表現サブマウントとして捕捉され、あなたはそれを代替品の$1として参照することができます最後に>が続きます。

+1

私はそれが働いていないことを試してみます。適用するともう一度を置き換えてください。 のように 'これは' –

1

使用

input.replace(/<[a-zA-Z]*>/g, '<span>$&</span>'); 

説明: .replaceは '' 内のすべてのタグを囲みます。 '$&がタグに置き換えられました。詳細はこれを参照してください。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

例:

var ta = document.getElementById('ta'), output = document.getElementById('output'); 
 
ta.value = 'I have <title> and <head> (this is just example text, you can replace).'; 
 
function replaceIt() { 
 
    output.innerText = ta.value.replace(/<[a-zA-Z]*>/g, '<span>$&</span>'); 
 
    // Okay, technically Node#innerText is non-standard, so use an HTML escape function on production sites. 
 
    // For demo purposes, I just chose innerText for ease of use 
 
}
<textarea id="ta"></textarea> 
 
<button onclick="replaceIt()">Enclose tags in &ltspan&gt s.</button> 
 
<div>Output:</div> 
 
<div id="output"></div>

+0

おかげで働いている...それはまた、 –

1

別の代替

var output = input.split("<").join("#").split(">").join("</span>").split("#").join("<span>"); 
console.log(output); 
+0

に取り組んでいる。スプリット(「@」) '冗長' .join(「@」)ではないですか? – nnnnnn

+0

さて、答えを投稿してからそれを見ました:)ありがとう。 – Jules

関連する問題