简体   繁体   English

仅将首次出现的内容替换为JavaScript

[英]Replace only first occurrence with javascript

I have a string that comes from HTML without tags but with escaped symbols, like: 我有一个来自HTML的字符串,其中没有标签,但带有转义的符号,例如:

abc&symbol1;def&symbol2;ghi&symbol3;jkl...

In JavaScript or TypeScript, how can I replace all sequences like &symbolN; 在JavaScript或TypeScript中,如何替换&symbolN;类的所有序列&symbolN; with one fixed character like X so I get: 具有一个固定的字符(例如X所以我得到:

abcXdefXghiXjkl...

(by the way, the target is to get the length of a string with distinct HTML escaped characters like £ so that each one of them is counted like one character) (顺便说一句,目标是获得带有£等不同HTML转义字符的字符串的长度,以便每个字符都像一个字符一样被计数)

Update : maybe I've not explained accurately: symbol1, symbol2,... do not mean that "symbol" string repeats, but completely distinct symbols that DO NOT repeat, eg "abc£def ghi€..." So no way to use a repeating textual pattern like "&symbol;" 更新 :也许我没有正确解释:symbol1,symbol2,...并不意味着重复“ symbol”字符串,而是不重复的完全不同的符号,例如“ abc£def ghi€...”使用重复的文本模式,例如“&symbol;”

Just to calculate length, you can cheat, as you say: 正如您所说,只是为了计算长度,您可以作弊:

html.replace(/&[^;]+;/, 'X').length

To convert HTML into text properly, one should use a HTML parser, not regexp. 为了将HTML正确地转换为文本,应该使用HTML解析器而不是regexp。 For example, in browser, 例如,在浏览器中,

let e = document.createElement('div');
e.innerHTML = html;
let text = e.textContent;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM