I'm trying to add span tags to each word of user's input for further manipulation. My attempt so far can only find english words and attach tags, how do I attach span tags to both to english words and Chinese Characters t if user's input has Chinese charecters within.
userInput="hello world 一些中文"
var regex = /(<.+?<\/.+?>|\S+)/g;
var result = userInput.replace(regex, function(a) {
return "<span id=" + (++id) + ">" + a + "</span>";
});
答案 0 :(得分:-1)
Use this regex instead
/[\u00ff-\uffff]|\S+/g
It is going to consider anything equal or greater than \u00ff
a word.
var id = 0;
var userInput="hello world 一些中文"
var regex = /[\u00ff-\uffff]|\S+/g;
var result = userInput.replace(regex, function(a) {
return `<span id="word${++id}">${a}</span>`;
});
document.getElementById('result').value = result;
input { width: 80%; }
<input type="text" id="result" />