Remove all characters after the last special character javascript - javascript

I have the following string.
var string = "Welcome, to, this, site";
I would like to remove all characters after the last comma, so that the string becomes
var string = "Welcome, to, this";
How do I go about it in Javascript? I have tried,
var string = "Welcome, to, this, site";
string = s.substring(0, string.indexOf(','));
but this removes all characters after the first comma.

What you need is lastIndexOf:
string = s.substring(0, string.lastIndexOf('?'));

you can use split and splice to achieve the result as below.
var string = "Welcome, to, this, site";
string = string.split(',')
string.splice(-1) //Take out the last element of array
var output = string.join(',')
console.log(output) //"welcome, to, this"

There's a String.prototype.lastIndexOf(substring) method, you can just use that in replacement of String.prototype.indexOf(substring) :
var delimiter = ",";
if (inputString.includes(delimiter)) {
result = inputString.substring(0, inputString.lastIndexOf(delimiter));
} else {
result = inputString;
}
Alternatives would include Madara Uchiha's suggestion :
var delimiter = ",";
var parts = inputString.split(delimiter);
if(parts.length > 0) { parts.pop(); }
result = parts.join(delimiter);
Or the use of regular expressions :
result = inputString.replace(/,[^,]*$/, "");

Try this
var string = "Welcome, to, this, site";
var ss = string.split(",");
var newstr = "";
for(var i=0;i<ss.length-1;i++){
if (i == ss.length-2)
newstr += ss[i];
else
newstr += ss[i]+", ";
}
alert(newstr);

Related

JavaScript replace string and comma if comma exists else only the string

I got a string like:
var string = "string1,string2,string3,string4";
I got to replace a given value from the string. So the string for example becomes like this:
var replaced = "string1,string3,string4"; // `string2,` is replaced from the string
Ive tried to do it like this:
var valueToReplace = "string2";
var replace = string.replace(',' + string2 + ',', '');
But then the output is:
string1string3,string4
Or if i have to replace string4 then the replace function doesn't replace anything, because the comma doens't exist.
How can i replace the value and the commas if the comma(s) exists?
If the comma doesn't exists, then only replace the string.
Modern browsers
var result = string.split(',').filter( s => s !== 'string2').join(',');
For older browsers
var result = string.split(',').filter( function(s){ return s !== 'string2'}).join(',');
First you split string into array such as ['string1', 'string2', 'string3', 'string4' ]
Then you filter out unwanted item with filter. So you are left with ['string1', 'string3', 'string4' ]
join(',') convertes your array into string using , separator.
Split the string by comma.
You get all Strings as an array and remove the item you want.
Join back them by comma.
var string = "string1,string2,string3,string4";
var valueToReplace = "string2";
var parts = string.split(",");
parts.splice(parts.indexOf(valueToReplace), 1);
var result = parts.join(",");
console.log(result);
You only need to replace one of the two commas not both, so :
var replace = string.replace(string2 + ',', '');
Or :
var replace = string.replace(',' + string2, '');
You can check for the comma by :
if (string.indexOf(',' + string2)>-1) {
var replace = string.replace(',' + string2, '');
else if (string.indexOf(string2 + ',', '')>-1) {
var replace = string.replace(string2 + ',', '');
} else { var replace = string.replace(string2,''); }
You should replace only 1 comma and also pass the correct variable to replace method such as
var string = "string1,string2,string3,string4";
var valueToReplace = "string2";
var replaced = string.replace(valueToReplace + ',', '');
alert(replaced);
You can replace the string and check after that for the comma
var replace = string.replace(string2, '');
if(replace[replace.length - 1] === ',')
{
replace = replace.slice(0, -1);
}
You can use string function replace();
eg:
var string = "string1,string2,string3,string4";
var valueToReplace = ",string2";
var replaced = string.replace(valueToReplace,'');
or if you wish to divide it in substring you can use substr() function;
var string = "string1,string2,string3,string4";
firstComma = string.indexOf(',')
var replaced = string.substr(0,string.indexOf(','));
secondComma = string.indexOf(',', firstComma + 1)
replaced += string.substr(secondComma , string.length);
you can adjust length as per your choice of comma by adding or subtracting 1.
str = "string1,string2,string3"
tmp = []
match = "string3"
str.split(',').forEach(e=>{
if(e != match)
tmp.push(e)
})
console.log(tmp.join(','))
okay i got you. here you go.
Your question is - How can i replace the value and the commas if the comma(s) exists?
So I'm assuming that string contains spaces also.
So question is - how can we detect the comma existence in string?
Simple, use below Javascript condition -
var string = "string1 string2, string3, string4";
var stringToReplace = "string2";
var result;
if (string.search(stringToReplace + "[\,]") === -1) {
result = string.replace(stringToReplace,'');
} else {
result = string.replace(stringToReplace + ',','');
}
document.getElementById("result").innerHTML = result;
<p id="result"></p>

Extracting end of String - Javascript

Say I have a string 12.13.14
How can I get the characters after the last dot. (in this case 14)?
There can be more than 2 characters.
Examples would be 34.45.657
10.11.46256
So after the last dot could be any amount of characters.
I've messed around with .slice() but can't get anywhere.
You have a bunch of options. One is split and pop:
var str = "12.13.14";
var last = str.split('.').pop();
document.body.innerHTML = last;
Another is a regular expression
var str = "12.13.14";
var match = /\.([^.]+)$/.exec(str);
var last = match && match[1];
document.body.innerHTML = last;
Or a rex and replace:
var str = "12.13.14";
var last = str.replace(/^.*\.([^.]+)$/, "$1");
document.body.innerHTML = last;
Or lastIndexOf and substring, as Ananth shows.
var str = '34.45.657';
console.log(str.substring(str.lastIndexOf('.') + 1));
You can do that in multiple ways:
First way:
var myString = '12.13.14';
var lastItem = myString.split('.').pop();
console.log(lastItem);
Second Way:
var myString = '12.13.14';
var lastItem = myString.slice(myString.lastIndexOf('.')+1);
console.log(lastItem);
Third Way:
var myString = '12.13.14';
var lastItem = myString.substring(myString.lastIndexOf('.') + 1);
console.log(lastItem);
and so on ,...
An easy solution would be to use split() which takes a delimiter.
You could split your string on dots and since split returns an array you could use pop() to get the last result.
e.g.
'34.345.3456'.split('.').pop(); // 3456
Easy solution to get your answer like this
var txt= document.getElementById("Text1").value;
var s1 = txt.lastIndexOf(".");
txt = txt.substring(0, s1);

How to get substring value from main string?

I have string similar to this one.
HTML
var str = "samplestring=:customerid and samplestring1=:dept";
JS
var parts = str.split(':');
var answer = parts;
I want to trim substrings which starts with colon: symbol from the main string
But it is returing the value like this
samplestring=,customerid and samplestring1=,dept
But I want it something like this.
customerid,dept
I am getting main string dynamically it may have colon more then 2.
I have created a fiddle also link
var str = "samplestring=:customerid and samplestring1=:dept";
alert(str.match(/:(\w+)/g).map(function(s){return s.substr(1)}).join(","))
you can try regex:
var matches = str.match(/=:(\w+)/g);
var answer = [];
if(matches){
matches.forEach(function(s){
answer.push(s.substr(2));
});
}
Here's a one-liner:
$.map(str.match(/:(\w+)/g), function(e, v) { return e.substr(1); }).join(",")
Try
var str = "samplestring=:customerid and samplestring1=:dept";
var parts = str.split(':');
var dept = parts[2];
var cus_id = parts[1].split(' and ')[0];
alert(cus_id + ", " + dept );
Using this you will get o/p like :customerid,dept
this will give you what you need...
var str = "samplestring=:customerid and samplestring1=:dept";
var parts = str.split(' and ');
var answer = [];
for (var i = 0; i < parts.length; i++) {
answer.push(parts[i].substring(parts[i].indexOf(':')+1));
}
alert(answer);
var str = "samplestring=:customerid and samplestring1=:dept";
alert(str.replace(/[^:]*:(\w+)/g, ",$1").substr(1))
You can try it like this
var str = "samplestring=:customerid and samplestring1=:dept and samplestring11=:dept";
var results = [];
var parts = str.split(' and ');
$.each(parts, function( key, value ) {
results.push(value.split(':')[1]);
});
Now the results array contains the three values customerid, dept, and dept
Here \S where S is capital is to get not space characters so it will get the word till first space match it, so it will match the word after : till the first space and we use /g to not only match the fisrt word and continue search in the string for other matches:
str.match(/:(\S*)/g).map(function(s){return s.substr(1)}).join(",")

Get characters before last space in string

Is there a way to obtain all characters that are after the last space in a string?
Examples:
"I'm going out today".
I should get "today".
"Your message is too large".
I should get "large".
You can do
var sentence = "Your message is too large";
var lastWord = sentence.split(' ').pop()
Result : "large"
Or with a regular expression :
var lastWord = sentence.match(/\S*$/)[0]
try this:
var str="I'm going out today";
var s=str.split(' ');
var last_word=s[s.length-1];
var x = "Your message is too large";
function getLastWord(str){
return str.substr(str.lastIndexOf(" ") + 1);
}
alert(getLastWord(x)); // output: large
// passing direct string
getLastWord("Your message is too large"); // output: large
use string.lastIndexOf():
var text = "I'm going out today";
var lastIndex = text.lastIndexOf(" ");
var result = '';
if (lastIndex > -1) {
result = text.substr(lastIndex+1);
}
else {
result = text;
}
UPDATE: Comment edited to add check if there's no space in the string.

Javascript regex help

I have the following string in JavaScript
var mystring = " abcdef(p,q); check(x,y); cef(m,n);"
I would want to do a string replace such that my final string is :
mystring = " abcdef(p,q); someothercheck\(x,y\); cef(m,n);"
x and y should remain same after the substitution. and the backslashes are necessary since I need to pass them to some other command.
There can be other Parantheses in the string too.
If you don't have other parenthesis, it should be easy.
mystring = mystring.replace("check(", "someothercheck\\(");
mystring = mystring.replace(")", "\\)");
EDIT This works also in the case of multiple parenthesis (It does not affect the empty ones).
var str=" abcdef; check(x,y); cef();"
patt = /((\w)/g;
// transform (x in \(x
str = str.replace(patt, '\\($1');
patt = /(\w)\)/g
// transform y) in y\);
str = str.replace(patt, '$1\\)');
// transform check in someothercheck
str = str.replace('check', 'someothercheck');
EDIT Now it converts only the check strings.
function convertCheck(str, check, someOtherCheck) {
// console.log(str + " contains " + check + "? ");
// console.log(str.indexOf(check));
if (str.indexOf(check) === -1) return str;
var patt1 = /\((\w)/g,
patt2 = /(\w)\)/g;
str = str.replace(patt1, '\\($1');
str = str.replace(patt2, '$1\\)');
str = str.replace(check, someOtherCheck);
return str;
}
var str = "abcdef(); check(x,y); cef();",
tokens = str.split(';');
for (var i = 0; i < tokens.length; i++) {
tokens[i] = convertCheck(tokens[i], "check", "someothercheck");
}
str = tokens.join(";");
alert(str); // "abcdef(); someothercheck/(x,y/); cef();"
var myString = "abcdef; check(x,y); cef;";
myString.replace(/(\w+)\(/, 'someother$1(')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)')

Categories

Resources