Javascript 如何查找字符串上的特定字母并使用

Javascript 如何查找字符串上的特定字母并使用,javascript,html,css,Javascript,Html,Css,我有一个p元素的字符串 这是我的字符串 我想用js在其中找到一个字母“s”,并更改它的颜色。您要完成的工作有几个部分。您已经获得了字符串: const myString = someDOMFunction(); // 'This is my string' 接下来,您需要找到该字符串中第一个的位置或“索引”: const sIndex = myString.indexOf('s'); // 3 然后可以使用该索引将字符串拆分为两部分: const leftPart = myString.su

我有一个p元素的字符串
这是我的字符串


我想用js在其中找到一个字母“s”,并更改它的颜色。

您要完成的工作有几个部分。您已经获得了字符串:

const myString = someDOMFunction(); // 'This is my string'
接下来,您需要找到该字符串中第一个
的位置或“索引”:

const sIndex = myString.indexOf('s'); // 3
然后可以使用该索引将字符串拆分为两部分:

const leftPart = myString.substr(0, sIndex); // 'Thi'
const rightPart = myString.substr(sIndex + 1); // ' is my string'
最后,您可以使用模板字符串语法构建包含这两部分的HTML(和CSS)字符串:

const html = `${leftPart}<span style="color:red">s</span>${rightPart}`;

应该将replace函数与正则表达式一起使用

const str = "<p>This is my string<p/>";

const newStr = str.replace(/s/g, '<span style="color:blue">s</span>');

您可以对p标记使用onchange($event),并获取p标记的innerHTML。获得innerHTML后,您可以运行条件并更改其颜色。只是提醒一下,您应该始终接受(即单击旁边的复选标记)最能回答您问题的答案(如果有)。。。即使不是我的:)
const str = "<p>This is my string<p/>";

const newStr = str.replace(/s/g, '<span style="color:blue">s</span>');
const str = "<p>This is my string<p/>";

function highlight(str, char) {
  const re = new RegExp(char, "g");
  return str.replace(re, `<span style="color:blue">${char}</span>`);
}

const newStr = highlight(str, "s");