删除指定位置的起始范围

时间:2015-10-29 18:37:00

标签: javascript

我需要定义要从第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之后

有可能吗?

4 个答案:

答案 0 :(得分:0)

一种解决方案是找到nth occurence,然后使用子字符串。



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('.')));




答案 1 :(得分:0)

当然,由" _"分开然后加入你想要的数据:

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

答案 2 :(得分:0)

正则表达式适用于这种情况:

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/

可能有一些不同的正则表达式方法可以完成工作

答案 3 :(得分:0)

也许这适合你:



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>
&#13;
&#13;
&#13;