删除从指定位置开始出现的范围

Removing a range starting occurrence with specified place

本文关键字:范围 开始 位置 定位 删除      更新时间:2023-09-26

我需要定义从第4次出现的(_)中删除的文本区域,并保留扩展名。

12_345_678_900_xxxxxxxxxxxxxxx.jpg之前12_345_678_900.jpg之后

34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg之前34_567_890_123.jpg 之后

有可能吗?

一种解决方案是找到第n次出现,然后使用子字符串。

var one='12_345_678_900_xxxxxxxxxxxxxxx.jpg'; // 12_345_678_900.jpg
function nth_occurrence (string, char, nth) {
    var first_index = string.indexOf(char);
    var length_up_to_first_index = first_index + 1;
    if (nth == 1) {
        return first_index;
    } else {
        var string_after_first_occurrence = string.slice(length_up_to_first_index);
        var next_occurrence = nth_occurrence(string_after_first_occurrence, char, nth - 1);
        if (next_occurrence === -1) {
            return -1;
        } else {
            return length_up_to_first_index + next_occurrence;  
        }
    }
}
console.log(one.substring(0,nth_occurrence(one,'_',4))+one.substring(one.indexOf('.')));

当然,用"_"分割,然后连接回您想要的数据:

var str = "12_345_678_900_xxxxxxxxxxxxxxx.jpg";
str = str.split("_").slice(0,4).join("_") + "."+ str.split(".").slice(-1)
console.log(str)

正则表达式非常适合这种场景:

const data1 = '12_345_678_900_xxxxxxxxxxxxxxx.jpg'
const data2 = '34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg'
const re = /^([^_]+_[^_]+_[^_]+_[^_]+).*(.jpg)$/;
var test1 = data1.replace(re, '$1$2');
var test2 = data2.replace(re, '$1$2');

试试看:https://jsfiddle.net/648xt3qq/

可能有几种不同的正则表达式方法可以完成任务

也许这对你有用:

function clean() {
    var el = document.getElementById('area');
    el.value = el.value.replace(/^(.*?_.*?_.*?_.*?)(_.*?)('..*?.*)$/gmi, '$1$3');
}
<form action="">
    <textarea cols="50" rows="4" id="area">12_345_678_900_xxxxxxxxxxxxxxx.jpg
34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg</textarea><br />
    <input type="submit" onclick="clean(); return false;" />
</form>