我想在一个字符串中设置一个单词(在这种情况下,字符串是"菠萝屋"首先在一个范围内包装该单词。如何在纯JavaScript中执行此操作?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input: <input type='text' id="txtInput"/>
我试过这个:
input: <div>pineapple house</div>
output: <div>pineapple <span id="word">house</span></div>
#word {
color: yellow;
}
但是这只是将一个对象放在字符串前面,而不是实际将该单词包装在一个范围
中答案 0 :(得分:1)
您可以通过以下方式完成此操作......
var input = '<div>pineapple house</div>';
var word = 'house';
var output = input.replace(new RegExp('(' + word + ')'), '<span id="word">$1</span>');
document.body.innerHTML += output; // append to page
#word {
color: red;
}
答案 1 :(得分:0)
以下适用于我,
var inp = 'pineapple house';
var word = 'house';
var out = inp.replace(word, "<span id='word'>" + word + "</span>");
console.log(out); // pineapple <span id='word'>{house}</span>
&#13;
答案 2 :(得分:0)
此版本使用ES6和正则表达式全局修饰符替换字符串中所有出现的单词。
let input = '<div>pineapple house, banana house, mango house</div>'; //Original string
let toReplace = 'house'; //Word to be replaced
let newWord = `<span class="word">${toReplace}</span>`; //Expression to replace the word with
let regEx = new RegExp(toReplace,"g"); //Regular Expression to find all occurrences of original word
let output = input.replace(regEx, newWord); //Replace all occurrences of the word
的console.log(输出);
<div>pineapple <span class="word">house</span>, banana <span class="word">house</span>, mango <span class="word">house</span></div>
然后你可以使用CSS类来设置所有出现的样式:
.word{
color: #ff0;
}