我不知道如何正确提问,但我需要获取 [] 标签内的文本并将其设为变量
狐狸前。我有:
<p>[something][written]</p>
我需要从 [something] 中获取单词 something 并将其设为 var [written] 也是如此,所以我可以有这样的东西:
var text1 = something /*-only the word-*/
var text2 = written /*-only the word-*/
像这样使用它:
<span>there is '+text1+' '+text2+' here.</span>
当然这不是我将如何使用它,但它们有点相似。是否可以?对不起,我完全是个新手。提前致谢。
最佳答案
您可以将 .text()
、.match()
与 RegExp
/\[[a-z]+\] 一起使用/ig
将 [text]
、.map()
、.replace()
与 RegExp
匹配> /\[|\]/
删除 [
, ]
字符
var [something, written] = $("p").text().match(/\[[a-z]+\]/ig)
.map((t) => t.replace(/\[|\]/g, ""));
console.log(something, written);
var span = `<span>there is ${something} ${written} here.</span>`;
$("body").append(span);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>[something][written]</p>
关于javascript - 使用javascript获取 '[ ]'标签内的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38864648/