如何在字符串的特殊字符之间找到字符串并将其替换为上标

时间:2018-09-17 06:51:13

标签: javascript jquery html

我有以下格式的标题-测试^ TM ^标题测试。我想以一种这样的方式转换此文本,即在'^'之间加上上标而不改变其位置,如下所示。

test TM 标题测试

请帮助我。

4 个答案:

答案 0 :(得分:2)

正则表达式可以为您做到这一点,请参见下面的示例。

const
  input = 'test ^TM^ title test',
  // This regex will match any text between two "^" characters. The text
  // between the "^" will be placed inside a capture group.
  regex = /\^(.*?)\^/g,  
  // This replaces the match with the text from the capture group, wrapped in a sup tag.
  htmlString = input.replace(regex, `<sup>$1</sup>`);
  
console.log(htmlString);
document.getElementById('output').innerHTML = htmlString;
<div id="output"></div>

答案 1 :(得分:0)

使用javascript:

text = "test ^TM^ title test";
text.replace(/\^(.+?)\^/g,'$1'.sup());

答案 2 :(得分:0)

我认为您需要在任何HTML或PHP编辑器中打开文件,并使用查找和替换选项。 例如:查找^ TM ^ 替换为: TM

答案 3 :(得分:0)

string = "hello^TM^ hi";
isOdd = true;
newString  = "";
for(i=0; i<string.length; i++){
    if(string[i] == '^'){
        if(isOdd){
            newString += "<sup>";
        } else {
            newString += "</sup>";
        }
        isOdd = !isOdd;
    } else{
        newString += string[i];
    }
}
//newString will have "hello<sup>TM</sup> hi"
相关问题