How to get substring after last specific character in JavaScript? - javascript

I have a string test/category/1. I have to get substring after test/category/. How can I do that?

You can use String.slice with String.lastIndexOf:
var str = 'test/category/1';
str.slice(0, str.lastIndexOf('/') + 1);
// => "test/category/"
str.slice(str.lastIndexOf('/') + 1);
// => 1

The actual code will depend on whether you need the full prefix or the last slash. For the last slash only, see Pedro's answer. For the full prefix (and a variable PREFIX):
var PREFIX = "test/category/";
str.substr(str.lastIndexOf(PREFIX) + PREFIX.length);

You can use below snippet to get that
var str = 'test/category/1/4'
str.substring(str.lastIndexOf('/')+1)

A more complete compact ES6 function to do the work for you:
const lastPartAfterSign = (str, separator='/') => {
let result = str.substring(str.lastIndexOf(separator)+1)
return result != str ? result : false
}
const input = 'test/category/1'
console.log(lastPartAfterSign(input))
//outputs "1"

var str = 'test/category/1';
str.substr(str.length -1);

You can use the indexOf() and slice()
function after(str, substr) {
return str.slice(str.indexOf(substr) + substr.length, str.length);
}
// Test:
document.write(after("test/category/1", "test/category/"))

var str = "test/category/1";
pre=test/category/;
var res = str.substring(pre.length);

You can use str.substring(indexStart(, indexEnd)):
var str = 'test/category/1';
var ln=str.length;
alert(str.substring(ln-1,ln));

Related

How to reverse value in javascript

hello I have values like this
1-10
2-3
901-321
I want to get the reverse values for example like this
10-1
3-2
321-901
I have tried this
var str = "1-18";
var newString = "";
for (var i = str.length - 1; i >= 0; i--) {
newString += str[i];
}
return newString;
But it gives me 81-1
Instead, use String.split(), Arrary.reverse() and Arrary.join():
var str = '901-321';
var strArray = str.split('-'); // ['901', '321']
var strArrayReversed = strArray.reverse(); // ['321', '901']
var result = strArrayReversed.join('-'); // '321-901'
console.log('result = ', result);
// You can do all these steps above in one go as:
var result2 = str.split('-')
.reverse()
.join('-');
console.log('result2 = ', result2);
MDN Docs:
String.prototype.split()
Array.prototype.reverse()
Array.prototype.join()
Can split on the - to create array , reverse the array and join it back into string
var str = "1-18",
newStr = str.split('-').reverse().join('-');
console.log(newStr)
a = "12-5"
console.log(a.split('-').reverse().join('-'))
You can use the split method to divide the string in two, and then use the second part before the first, like this:
var str = "1-18";
var l = str.split("-");
return l[1] + "-" + l[0];
You could replace the string by swapping the values.
var string = '901-321';
console.log(string.replace(/(.+)-(.+)/, '$2-$1'));

Javascript regex match number after string

I have this string
/results?radius=4000&newFilter=true
and I need to replace radius=4000 with radius=n where n is a variable.
How can I use String.replace() method with regex to match that part?
You can use /radius=\d+/ to match "radius=" followed by any number of digits. With this we can use the replace() method to replace it with the desired value:
var str = "/results?radius=4000&newFilter=true";
var replacement = 123;
var newStr = str.replace(/radius=\d+/, "radius=" + replacement);
console.log(newStr);
If you want to get all parameters you can try this :
function getParams(uri) {
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(uri)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
var str='/results?radius=4000&newFilter=true';
str = str.substring(str.indexOf("?"));
params = getParams(str);
console.log(params);
console.log('radius => ', params['radius']);
This answer is from this post: How to get the value from the GET parameters?
It should be as easy as
var str='/results?radius=4000&newFilter=true';
var n = 1234;
str = str.replace(/(radius=)(\d+)/, "$1" + n);
var url = "/results?radius=4000&newFilter=true";
// or window.location.href for current url
var captured = /radius=([^&]+)/.exec(url)[1]; // your 4000
var newValue = 5000;
url = url.replace(captured, newValue);
by this way you can use it to get all your requested parameters too
and it is not decimal binded
ES6 with regex using positive lookbehind
const string = '/results?radius=4000&newFilter=true',
n = '1234',
changeRadius = (radius) => string.replace(/(?<=radius=)\d+/, n);
console.log(changeRadius(n));
/* Output console formatting */
.as-console-wrapper { top: 0; }
changeRadius is function that takes one parameter (radius) and performs replacement.
About the regex: \d+ gets as many digits as possible, (?<=STRING) is a positive lookbehind.
Other regex
Body of changeRadius() function can be replaced with string.replace(/radius=\d+/, 'radius=' + n). It probably has better performance, but original regex is more direct translation of the problem.
You can use capturing without remembering the match to capture only the numerical value after 'radius='.
var url = "/results?radius=4000&newFilter=true";
var radius = 123;
var newUrl = url.replace(/(?:radius=){1}(\d+)/, radius);
console.log(newUrl); // logs '/results?radius=4000&newFilter=true'0
'

Javascript-split() not working when there are repeated chars in a string

Not sure how valid is this approach, but I'm unable to split the string into 2 when there are repeated characters.
var match = 's';
var str = "message";
var res = str.split(match, 2);
For instance i tried to use split() on the string "message", it results into:
me,""
So i did this:
res = str.split(match, 3);
so now it resulted into:
me,,age
but as you can see im still missing the second 's' in the "message" string. what im trying to get is I'm passing a matched character (in above case var match which is dynamically generated) to the split() and splitting into 2. I was hoping to get something this:
res = me,,sage
is that possible using split() or is there a better method to achieve this?
P.S: in fiddle i've given another string eg: (string = "shadow") which works fine.
Fails only when there are repeated letters in the string!
fiddle: https://jsfiddle.net/ukeeq656/
EDIT::::::::::::
Thanks everyone for helping me out on this...and so sorry for last min update on the input, i just realized that var match; could be a word too, as in var match = 'force'; and not just var match ='s'; where the string is "forceProduct", so when my match is more than just a letter, this approach works: str.split(match, 2);, but str.indexOf(match); doesnt obviously... could there be an approach to split: "","Product". My extreme apologies for not mentioning this earlier.any help on this would be appreciated!!
eg fiddle:
https://jsfiddle.net/ukeeq656/3/
I don't think split() is the correct way to do this.
Please see below:
var match = 's';
var str = "message";
var index = str.indexOf(match);
var res =[];
res[0] = str.substring(0, index);
res[1] = " ";
res[2] = str.substring(index + 1);
console.log(res);
I'm not sure what your end goal is but I think this gets you what you want.
var match = 's';
var str = "message";
var index = str.indexOf(match);
var res = str.substring(0, index) + ',' + str.substring(index + 1);
alert(res); // me,sage
You could write a function to do this;
function newSplit(str, match) {
var num = str.indexOf(match);
var res = [];
res.push(str.substring(0, num));
//res.push(str.substring(num + 1, str.length)); // this line has been modified
res.push(str.substring(num + match.length, str.length));
return res;
}
var match = 'force';
var str = 'forceProduct';
console.log(newSplit(str, match));
This is what you want?

How can I get this result in RegEx using Javascript

If my entry is "001.1-2016", I want "001.2-2016"
If my entry is "001.8-2015", I want "001.9-2016"
If my entry is "001.12-2014", I want "001.13-2016"
If my entry is "001.123-2016", I want "001.124-2016"
I tried a regex like this:
([0-9]{3}\.)(.*)(\-[0-9]{4})
but this get all, I want only the middle.
Your regex (\[0-9\]{3}\.)(.*)(\-\[0-9\]{4}) works fine, you just need to get the second captured group result.
var arr = ["001.1-2016", "001.8-2015", "001.12-2014", "001.123-2016"];
var regex = /([0-9]{3}\.)(.*)(\-[0-9]{4})/;
arr.forEach(function(str) {
document.body.innerHTML += str.match(regex)[2] + '<br />';
});
You can use String#split and parseInt.
var value = "001.12-2014";
var num = parseInt(value.split('.')[1], 10);
var value = "001.12-2014";
var num = parseInt(value.split('.')[1], 10);
document.body.innerHTML = num;
Using Regex
var value = "001.12-2014";
var num = value.match(/.*?\.(\d+)/)[1];
var value = "001.12-2014";
var num = (value.match(/.*?\.(\d+)/) || [])[1];
document.body.innerHTML = num;
I need just add +1 in this number, eg. "001.12-2014" >>> "001.13-2014" or "001.123-2014" >>> "001.124-2014"
var arr = ["001.1-2016", "001.8-2015", "001.12-2014", "001.123-2016"];
arr = arr.map(e => e.replace(/\.(\d+)/, ($0, $1) => '.' + (1 + +$1)));
document.body.innerHTML = arr;
To increment the number by 1 you can use String#replace
document.getElementById('input').addEventListener('keyup', function() {
var value = this.value;
value = value.replace(/\.(\d+)/, function($0, $1) {
return '.' + (1 + +($1 || 0));
});
document.getElementById('output').innerHTML = value;
}, false);
<input type="text" id="input" />
<pre id="output"></pre>
The regex pattern could be
/[0-9]+\.([0-9]+)\-[0-9]+/g
if you do not concern the number format before . and after -
You can test it on here.
Try to use split method .The split() method splits a String object into an array of strings by separating the string into substrings.
<script>
function myFunction() {
var str = "001.12-2014";
var res = new Array();
res=str.split(".");
var finalres=res[1].split("-",1);
document.getElementById("demo").innerHTML = finalres;
}
</script>
Output:
this matches all 4 (find the decimal and take one or more digits that follow):
/\.(\d+)/g
# https://regex101.com/r/qG2mX7/4

How to replace all dots in a string using JavaScript

I want to replace all the occurrences of a dot(.) in a JavaScript string
For example, I have:
var mystring = 'okay.this.is.a.string';
I want to get: okay this is a string.
So far I tried:
mystring.replace(/./g,' ')
but this ends up with all the string replaced to spaces.
You need to escape the . because it has the meaning of "an arbitrary character" in a regular expression.
mystring = mystring.replace(/\./g,' ')
One more solution which is easy to understand :)
var newstring = mystring.split('.').join(' ');
/**
* ReplaceAll by Fagner Brack (MIT Licensed)
* Replaces all occurrences of a substring in a string
*/
String.prototype.replaceAll = function( token, newToken, ignoreCase ) {
var _token;
var str = this + "";
var i = -1;
if ( typeof token === "string" ) {
if ( ignoreCase ) {
_token = token.toLowerCase();
while( (
i = str.toLowerCase().indexOf(
_token, i >= 0 ? i + newToken.length : 0
) ) !== -1
) {
str = str.substring( 0, i ) +
newToken +
str.substring( i + token.length );
}
} else {
return this.split( token ).join( newToken );
}
}
return str;
};
alert('okay.this.is.a.string'.replaceAll('.', ' '));
Faster than using regex...
EDIT:
Maybe at the time I did this code I did not used jsperf. But in the end such discussion is totally pointless, the performance difference is not worth the legibility of the code in the real world, so my answer is still valid, even if the performance differs from the regex approach.
EDIT2:
I have created a lib that allows you to do this using a fluent interface:
replace('.').from('okay.this.is.a.string').with(' ');
See https://github.com/FagnerMartinsBrack/str-replace.
str.replace(new RegExp(".","gm")," ")
For this simple scenario, i would also recommend to use the methods that comes build-in in javascript.
You could try this :
"okay.this.is.a.string".split(".").join("")
Greetings
I add double backslash to the dot to make it work. Cheer.
var st = "okay.this.is.a.string";
var Re = new RegExp("\\.","g");
st = st.replace(Re," ");
alert(st);
replaceAll(search, replaceWith) [MDN]
".a.b.c.".replaceAll('.', ' ')
// result: " a b c "
// Using RegEx. You MUST use a global RegEx.
".a.b.c.".replaceAll(/\./g, ' ')
// result: " a b c "
replaceAll() replaces ALL occurrences of search with replaceWith.
It's actually the same as using replace() [MDN] with a global regex(*), merely replaceAll() is a bit more readable in my view.
(*) Meaning it'll match all occurrences.
Important(!) if you choose regex:
when using a regexp you have to set the global ("g") flag;
otherwise, it will throw a TypeError: "replaceAll must be called with
a global RegExp".
This is more concise/readable and should perform better than the one posted by Fagner Brack (toLowerCase not performed in loop):
String.prototype.replaceAll = function(search, replace, ignoreCase) {
if (ignoreCase) {
var result = [];
var _string = this.toLowerCase();
var _search = search.toLowerCase();
var start = 0, match, length = _search.length;
while ((match = _string.indexOf(_search, start)) >= 0) {
result.push(this.slice(start, match));
start = match + length;
}
result.push(this.slice(start));
} else {
result = this.split(search);
}
return result.join(replace);
}
Usage:
alert('Bananas And Bran'.replaceAll('An', '(an)'));
String.prototype.replaceAll = function(character,replaceChar){
var word = this.valueOf();
while(word.indexOf(character) != -1)
word = word.replace(character,replaceChar);
return word;
}
Here's another implementation of replaceAll. Hope it helps someone.
String.prototype.replaceAll = function (stringToFind, stringToReplace) {
if (stringToFind === stringToReplace) return this;
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};
Then you can use it:
var myText = "My Name is George";
var newText = myText.replaceAll("George", "Michael");
Example: I want to replace all double Quote (") into single Quote (') Then the code will be like this
var str= "\"Hello\""
var regex = new RegExp('"', 'g');
str = str.replace(regex, '\'');
console.log(str); // 'Hello'
#scripto's made a bit more concise and without prototype:
function strReplaceAll(s, stringToFind, stringToReplace) {
if (stringToFind === stringToReplace) return s;
for (let index = s.indexOf(stringToFind); index != -1; index = s.indexOf(stringToFind))
s = s.replace(stringToFind, stringToReplace);
return s;
}
Here's how it stacks up: http://jsperf.com/replace-vs-split-join-vs-replaceall/68
String.prototype.replaceAll = function (needle, replacement) {
return this.replace(new RegExp(needle, 'g'), replacement);
};
mystring.replace(new RegExp('.', "g"), ' ');
Simplest way
"Mr.".split('.').join("");
..............
Console
you can replace all occurrence of any string/character using RegExp javasscript object.
Here is the code,
var mystring = 'okay.this.is.a.string';
var patt = new RegExp("\\.");
while(patt.test(mystring)){
mystring = mystring .replace(".","");
}
let a = "once there was a king. spread opeator. let. ver. const.";
let data = a.replaceAll(".","");
Answer : data = "once there was a king spread opeator let ver const";
You need to use replaceAll() method on that string.
var mystring = 'okay.this.is.a.string';
var myNewString = escapeHtml(mystring);
function escapeHtml(text) {
if('' !== text) {
return text.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/\./g,' ')
.replace(/"/g, '"')
.replace(/&#39/g, "'");
}

Categories