Javascript 条件查找/替换

Javascript conditional find/replace

本文关键字:替换 查找 条件 Javascript      更新时间:2023-09-26

对于我的javascript项目,我有一个如下所示的列表:

<li id="1">101.33, "book name 1"</li>
<li id="2">600.01, book name 2</li>
<li id="3">001.11, book name 3</li>
etc...

其中我应该做以下几点:

  1. 将项目符号列表条目重新映射到新的(一致)标记类型(您的选择 - 使其看起来漂亮!
  2. 对于介于 100 和 200 之间的条目,在杜威十进制数中添加 100。
  3. 对于介于 400 和 500 之间的条目,请在杜威十进制数中添加 200。
  4. 介于 850 和 900 之间的条目需要从杜威十进制数中删除 100。
  5. 介于 600 和 650 之间的条目需要在杜威十进制数中添加 17
  6. 对于已更改的项目,将"已更改"附加到记录中。
  7. 对于未更改的项目,请将"无更改"附加到记录中。
  8. 对于不正确的记录,将"无效记录"附加到记录中

但我不确定该怎么做。我想定位正文或列表项中的任何数字。现在我有这个:

var z = document.body.li.innerHTML;
if (z >+ 100 && z <= 200)
{
var q = z + 100;
document.body.li.innerHTML=q;
}
}

谁能指出我在javascript中做到这一点的最佳方法的正确方向?我应该改用查找/替换吗?

编辑:试图修改David Thomas代码中的最后一个三元ifelse语句。似乎无法让它工作:

//define valid record number as at-least-one-integer.at-least-one-integer
var reggie = /'d+(.)+d/
if (_newText = reggie) {
'Invalid Record';
}
else if (_newText === a[textProp]) {
'no change';
}
else(_newText != a[textProp]) {
'changed';
}
+ ')';

一种方法如下(使用纯JavaScript,尽管您需要使用最新的浏览器):

// first, we need to get all the 'li' items:
var lis = document.querySelectorAll('ul > li'),
    // find the relevant text-property for this browser:
    textProp = 'textContent' in document ? 'textContent' : 'innerText',
    // empty string variable to allow assessment of changes:
    _newText = '';
// Remap the bullet list entries to a new (consistent) tag type (your choice – make it look pretty!).
// do this one yourself.
// a function to zero-pad the numbers (I believe a requirement of Dewey Decimal):
function leftPadNumber(num, numLength, padChar) {
    var nString = num.toString(),
        major = parseInt(num, 10),
        minor = parseFloat(nString.substring(nString.indexOf('.'))),
        diff = numLength - major.toString().length;
    if (diff > 0) {
        return new Array(diff + 1).join(padChar || 0) + (major + minor);
    } else {
        return num;
    }
}
// For entries between 100 and 200, add 100 to the Dewey decimal number.
// For entries between 400 and 500, add 200 to the Dewey decimal number.
// Entries between 850 and 900 need to have 100 removed from the Dewey decimal number.
// Entries between 600 and 650 need to have 17 added to the Dewey decimal number
// note that I've taken a very literal interpretation of 'between' (amend if necessary):
function amendedDeweyDecimal(num) {
    if (num > 100 && num < 200) {
        num += 100;
    } else if (num > 400 && num < 500) {
        num += 200;
    } else if (num > 850 && num < 900) {
        num -= 100;
    } else if (num > 600 && num < 650) {
        num += 17;
    }
    // happens if num falls somewhere outside of the above constraints:
    return num;
}
// iterates over each element in the 'lis' nodeList/collection:
[].forEach.call(lis, function (a) {
    /* replaces the found numbers ('m') in the string, using the two
       functions, above, and assigns those to the _newText variable:
    _newText = a[textProp].replace(/('d{3}'.'d{2})/, function (m) {
        return leftPadNumber(amendedDeweyDecimal(parseFloat(m)).toFixed(2), 3);
    });
    // For items that get changed, append “changed” to the record.
    // For items that do not get changed, append “no change” to the record.
    // returns the original text to the element, along with '(no change)'
    // (if 'a[textProp]' is exactly equal to '_newText') or with '(changed)'
    // (if the two variables are not identical):
    a[textProp] = _newText + ' (' + (_newText === a[textProp] ? 'no change' : 'changed') + ')';
});
// For records that are incorrect, append “invalid record” to the record
// I have absolutely no idea how to assess an 'incorrect' record.

JS小提琴演示。

引用:

  • Array.prototype.forEach() .
  • document.querySelectorAll() .
  • Number.toFixed() .
  • Number.toString() .
  • String.parseFloat() .
  • String.parseInt() .
  • String.replace() .

试试 jQuery .each

$('li').each(function(index, value) {
    var val = $(this).text().split(','); //split into array
    if (index >= 100 && index < 200) {
        //do stuff
    }
    if (index >= 400 && index < 500) {
        //do stuff
    }
    //etc
});

无论你是想使用纯JavaScript还是辅助库(例如jQuery)来解决这个问题,我都建议把你的问题拆解成更小的任务,然后一个接一个地解决。最后,他们将一个安装到另一个,并将构建完整的解决方案。我会从三个简单的函数开始(阅读您的描述,它们将经常需要):

  • 能够单独列出所有 LI 元素
  • 从 LI 内容中提取数字
  • 检查数字是否在给定范围内

代码可能如下所示:

// count of all LI items
var elements = 0; 
// fetch LI item one at a time
var element = document.getElementById(elements+1);
while (element != undefined) {
    // get the number
    var number = Number(getNumber(element.innerHTML));
    // do something with number and or LI element
    if (inRange(number, 100, 200)) { /* add 100 ...*/ } // and so on
    // go to next element
    elements++;
    element = document.getElementById(elements+1);
}
function getNumber(elementContent) {
    return elementContent.split(",")[0]; // TODO error handling
}
function inRange(number, min, max) {
    return (number >= min) && (number <= max);
}

您可以引入简单的对象和数组来存储信息和状态,以跟踪内容的更改。