简体   繁体   中英

How to remove tag between string using javascript

I want to download directions panel as a text file from Google maps API. I did successfully but that text file has HTML tag also.I only need that directions string.

How I can remove that string using java script?

Any help would be appreciated.

Thanks for advance.

My code here,

function saveTextAsFile(response) {
    var firstPath = response.routes[0].legs[0].steps;
    var textContent = "";

    for (var index in firstPath) {
        var ins = firstPath[index].instructions;
        textContent += ins + "\n";
    }

    location.href = 'data:application/downloads,' + encodeURIComponent(textContent)
}

I got output like these:

Head <b>south</b> on <b>Pallavaram Kundrathur Main Rd/Pammal Main Rd</b> toward <b>Vedagiri St</b><div style="font-size:0.9em">Pass by SBI ATM (on the right)</div>
Turn <b>right</b> onto <b>Indira Gandhi Rd</b><div style="font-size:0.9em">Pass by Canara Bank (on the left in 350&nbsp;m)</div>
Turn <b>right</b> at <b>Pallavaram Signal</b> onto <b>NH45</b><div style="font-size:0.9em">Pass by DCB Bank Atm - Pallavaram Branch (on the left)</div>
Turn <b>left</b> onto <b>Dharga Rd</b>
Turn <b>left</b> toward <b>Siva Sankaran St</b>
Take the 1st <b>right</b> toward <b>Siva Sankaran St</b>
Take the 1st <b>left</b> onto <b>Siva Sankaran St</b>
Slight <b>right</b> at <b>Pedistrian Crossing</b>
Turn <b>right</b> toward <b>Subramaniar Koil 2nd St</b>
Turn <b>left</b> onto <b>Subramaniar Koil 2nd St</b>

but i need without that html tag

This similar question gives a few good ways to strip HTML tags from a string, my personal favorites being :

  • Using RegEx: textContent.replace(/<[^>]*>?/gm, '');
  • Using jQuery: jQuery(textContent).text();

I've modified your function to do what you need

function saveTextAsFile(response) {
    var firstPath = response.routes[0].legs[0].steps;
    var textContent = "";

    for (var index in firstPath) {
        var ins = firstPath[index].instructions;
        textContent += ins.replace(/<(?:.|\n)*?>/gm, ''); + "\n";
    }

    location.href = 'data:application/downloads,' + encodeURIComponent(textContent)
}

To remove just the tags the following should work

function saveTextAsFile(response) {
    var firstPath = response.routes[0].legs[0].steps;
    var textContent = "";

    for (var index in firstPath) {
        var ins = firstPath[index].instructions;
        textContent += ins.replace(/<\/?[b]>/gm, '');
    }

    location.href = 'data:application/downloads,' + encodeURIComponent(textContent)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM