0

I need to define the text area to delete from 4th occurrence of (_) and preserve the extension.

before 12_345_678_900_xxxxxxxxxxxxxxx.jpg after 12_345_678_900.jpg,

before 34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg after 34_567_890_123.jpg

Is it possible?

Mi-Creativity
  • 9,554
  • 10
  • 38
  • 47
Luiz
  • 1
  • 1

4 Answers4

0

One solution is to find the nth occurence and then use substring.

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('.')));
Community
  • 1
  • 1
depperm
  • 10,606
  • 4
  • 43
  • 67
0

Sure, split by "_" and then join back the data you want:

var str = "12_345_678_900_xxxxxxxxxxxxxxx.jpg";
str = str.split("_").slice(0,4).join("_") + "."+ str.split(".").slice(-1)
console.log(str)
juvian
  • 15,875
  • 2
  • 37
  • 38
0

Regular Expressions are great for this sort of scenario:

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

Try it out: https://jsfiddle.net/648xt3qq/

There are probably a few different regular expression approaches that would get the job done

Jared Dykstra
  • 3,596
  • 1
  • 13
  • 25
0

Maybe this works for you:

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>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392