Subtract two strings in javascript

Go To StackoverFlow.com

0

kwd variable holds this value: news path:".aspx" It is basically the query string of an url.

  var path= "path:\".aspx\""; 

so kwd= whatever user types passed to the url like this+path:

kwd=news path:".aspx";

I need to subtract kwd-path so i get only "news" How do i do that in java-script or jquery?

I know i can either use trim or substring or substr.. But I couldn't get to work . I am basically using this logic:

if (b.startsWith(a)) {
        return b.subString(a.length());
    }

    if (b.endsWith(a)) {
        return b.subString(0, b.length() - a.length());
    }

But this is not working..

 var persistvalue= kwd.subString(0, kwd.length() - path.length());
2012-04-05 20:18
by Anjana Sharma
Can you simply replace with empty string? 'b.replace(a, ''); - Chris Gessler 2012-04-05 20:22


0

kwd.length() - path.length() - isn't this value negative?

try path.length() - kwd.length()

2012-04-05 20:21
by ninjagecko


0

Since your .aspx is inside a string, you must first extract it from the string:

>>> 'an example:"some text"'.match(/"(.*)"/)[1]
"some text"

Now you can remove a string if it appears at the end:

function removeFromEnd(string, toRemove) {
    function literally(regexp) {
        regexp.replace(/./g, function(x){return '\\'+x})
    }
    yourString.replace(RegExp(literally(string)+'$'), '')
}

The $ means the end-of-string. Alternatively you can do it much more simply with:

function removeFromEnd(string, toRemove) {
    if (string.slice(-toRemove.length)==toRemove)
        return string.slice(0, -toRemove.length);
    else
        return string
}
2012-04-05 20:24
by ninjagecko
Ads