替换字符串值并使用 JavaScript 保留部分替换字符串



>我有一个 reach 文本框,用户可以在其中设计一个 html 页面,我无法访问 TextArea 的事件键控或键下键,所以我无法在运行时更改用户输入数字的输入,所以我最终会得到一个包含各种 HTML 标签的 reachText 值,并且 reachText 值中允许任何 HTML 标签,现在我想将用户在文本中输入的任何数字更改为 Word,这意味着如果用户输入 1,我希望它是单词 (一) 和 2,3,4。等等,但与此同时,我想保持 html 标签中的数字不变,没有变化,以保持用户对他设计的 reach 文本所做的样式,例如,如果我有以下生成的 HTML:

<h1>Title1: Hi iam first title</h1><h3>Title3 hi iam third title</h3>
<div style='width:23px'>iam a div with 23 pixels width</div>

这只是一个示例,但用户可以构造任何 HTML 设计、样式和标签,因此输入可能会有所不同,并且比此示例更复杂。使用javascript,我想将其更改为:

<h1>Titleone: Hi iam first title</h1><h3>Titlethree hi iam third title</h3>
<div style='width:23px'>iam a div with twothree pixels width</div>

var oldValue = '<h1>Title1: Hi iam first title</h1><h3>Title3 hi iam third title</h3>
<div style='width:23px'>iam a div with 23 pixels width</div>';
var newValue = oldValue.replace(/1|2|3/g, function convertNumbers(x) {
    switch (x) {
        case '1':
            return 'one';
            break;
        case '2':
            return 'two';
            break;
        case '3':
            return 'three';
            break;
    }
});

但是这段代码的结果

<hone>Titleone: Hi iam first title</hone><hthree>Titlethree hi iam third title</hthree>
<div style='width:twothreepx'>iam a div with twothree pixels width</div>

我尝试使用正则表达式仅替换任何( > ) 和 ( < ) 但不知道如何构造正则表达式,请帮忙。现在我想指定一种模式,该模式仅替换 HTML 中的文本,并且不更改 HTML 标签的样式或属性中的数字,在我看来,可以通过使用正则表达式找到一种模式来完成,以获取左侧有">"和右侧有"<"的文本,例如:

<h1>Title1: Hi iam first title</h1>

如果我通过获取左侧有">"和右侧有"<"的字符串来应用上一个字符串的模式,我只会得到"Title1:嗨,我是第一个标题",所以我将替换在这个结果字符串中找到的数字以获得我想要的输出。是否有可能,或者我必须重新考虑使用正则表达式并找到另一种方法来完成任务?

您可以使用 jQuery text(function) 方法来更新元素的 innerText。

// To store the string representation of the digits
var num = [undefined ,'one', 'two', 'three'];
// Iterate over all the `<h1>`, `<h3>`
$('h1, h3').text(function(i, text) {
    // Match 1, 2 or 3. Regex can also be written as `[123]` or `[1-3]`
    return text.replace(/1|2|3/g, function(number) {
        return num[number]; // Replace by the textual representation.
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<h1>Title1</h1><h3>Title3</h3>

您可以使用

RegExp /(1|2|3)(?!>)/g来匹配123如果字符后没有>字符

var oldValue = '<h1>Title1</h1><h3>Title3</h3>';
var newValue = oldValue.replace(/(1|2|3)(?!>)/g, function convertNumbers(x) {
  switch (x) {
    case '1':
      return 'one';
      break;
    case '2':
      return 'two';
      break;
    case '3':
      return 'three';
      break;
  }
});
document.write(newValue)

最新更新