How to replace or strip the [number] from string with jquery - javascript

The value of selected variable is "Topic [9]" or "Category [10]". i want to remove "[number]" from the value of selected variable?
selected = $('#topic_id option:selected').text();
i think, i can strip value with replace() as follows but need to know, how do i achieve because number is not fixed.
selected = $('#topic_id option:selected').text().replace();

This has nothing to do with jQuery but with pure Javascript. Just use regex, like this one \[.+ to do it.
selected = $('#topic_id option:selected').text().replace(/\[.+/g, "");
Demo.
Of course this only works on the pattern you have provided: With [number] at the end of the string.
UPDATE: As #Zack pointed on the comments, you can use this regex \s\[.+ to remove the space before the [.

Ohjay44 was onto something with the split, but didn't provide an answer, so I went ahead.
This solution will split the selected string by the space character, then call pop() which removes the last element of the array, then it uses join(" ") which returns the elements of an array as a string, concatenated with the provided seperator, or , if none is provided.
Here is a working example on jsfiddle.net http://jsfiddle.net/jX36T/
var selected = "Topic of conversation [9]";
var splitted = selected.split(" ");
splitted.pop();
var string = splitted.join(" ");
alert(stringResult);
Displays "Topic of conversation"

If you only have one word to get, you can explode with the space character and keep the first item of the returned array

Related

Split and grab text before second hyphen

I have the following text string:
test-shirt-print
I want to filter the text string so that it only returns me:
test-shirt
Meaning that everything that comes after the second hyphen should be removed including the hyphen.
I am thinking that the solution could be to split on hyphen and somehow select the two first values, and combine them again.
I am unaware of which functionality is best practice to use here, I also thinking that if it would be possible to use a regular expression in order to be able to select everything before the second hyphen.
You can use split slice and join together to remove everything after the second hyphen
var str = "test-shirt-print";
console.log(str.split("-").slice(0, 2).join('-'))
You can try with String.prototype.slice()
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
and String.prototype.lastIndexOf()
The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found.
var str = 'test-shirt-print';
var res = str.slice(0, str.lastIndexOf('-'));
console.log(res);
You can also use split() to take the first two items and join them:
var str = 'test-shirt-print';
var res = str.split('-').slice(0,2).join('-');
console.log(res);

How to remove second whitespace in string, but not first using js

I have a small text field and if there is more than one whitespace I need to format the string and add a br tag in that second whitespace. If there isn;t then I do not need to do anything. I do not need to target the first or third (if there is one) and there will probably not be any after 3 as this is a short title field. the length of characters will be different and there is not consistent marker, like a comma of period or something, that I can target.
I was unable to find an answer that addressed this. I did find answers using regex but those all had markers like comma to target, I cannot find on that specifically will only target the second occurrence if there is one so any help would be great appreciated.
Code I have now, which targets only the first occurrence.
Array.prototype.forEach.call(awardscount, function() {
var string = $('#award-' + int).attr('data-award-title');
var refomrattedTitle = string.replace(" ", "<br>");
int++;
console.log(refomrattedTitle);
});
var test = "foo bar string test".replace(/([^\s]*\s[^\s]*)\s/, "$1<br/>");
console.log(test); // logs "foo bar<br/>string test"

how to remove first special character from string

I have values seperated by pipes in a database. But the issue is that I am appending | at every entry.
For Example:
|275634|374645|24354|
How can I remove the first pipe from the whole string not all the pipes.
Once inserted I don't need to check for the next time when it updates.
If I use substring(1) then it will remove the first character every time,
Please suggest a fix?
//input = '|275634|374645|24354|';
output = input.replace('|', '');
String#replace will replace the first occurance in a String. If you replace it with an empty String '' it is removed.
jsFiddle
you can use substring(index) method where ever you want to remove the perticular special character from the String: like
String str2 = "|275634|374645|24354|";
str2 = str2.substring(1);
System.out.println(str2);
you can see the output as 275634|374645|24354|

Parse string regex for known keys but leave separator

Ok, So I hit a little bit of a snag trying to make a regex.
Essentially, I want a string like:
error=some=new item user=max dateFrom=2013-01-15T05:00:00.000Z dateTo=2013-01-16T05:00:00.000Z
to be parsed to read
error=some=new item
user=max
dateFrom=2013-01-15T05:00:00.000Z
ateTo=2013-01-16T05:00:00.000Z
So I want it to pull known keywords, and ignore other strings that have =.
My current regex looks like this:
(error|user|dateFrom|dateTo|timeFrom|timeTo|hang)\=[\w\s\f\-\:]+(?![(error|user|dateFrom|dateTo|timeFrom|timeTo|hang)\=])
So I'm using known keywords to be used dynamically so I can list them as being know.
How could I write it to include this requirement?
You could use a replace like so:
var input = "error=some=new item user=max dateFrom=2013-01-15T05:00:00.000Z dateTo=2013-01-16T05:00:00.000Z";
var result = input.replace(/\s*\b((?:error|user|dateFrom|dateTo|timeFrom|timeTo|hang)=)/g, "\n$1");
result = result.replace(/^\r?\n/, ""); // remove the first line
Result:
error=some=new item
user=max
dateFrom=2013-01-15T05:00:00.000Z
dateTo=2013-01-16T05:00:00.000Z
Another way to tokenize the string:
var tokens = inputString.split(/ (?=[^= ]+=)/);
The regex looks for space that is succeeded by (a non-space-non-equal-sign sequence that ends with a =), and split at those spaces.
Result:
["error=some=new item", "user=max", "dateFrom=2013-01-15T05:00:00.000Z", "dateTo=2013-01-16T05:00:00.000Z"]
Using the technique above and adapt your regex from your question:
var tokens = inputString.split(/(?=\b(?:error|user|dateFrom|dateTo|timeFrom|timeTo|hang)=)/);
This will correctly split the input pointed out by Qtax mentioned in the comment: "error=user=max foo=bar"
["error=", "user=max foo=bar"]

Remove string after predefined string

I am pulling content from an RSS feed, before using jquery to format and edit the rss feed (string) that is returned. I am using replace to replace strings and characters like so:
var spanish = $("#wod a").text();
var newspan = spanish.replace("=","-");
$("#wod a").text(newspan);
This works great. I am also trying to remove all text after a certain point. Similar to truncation, I would like to hide all text starting from the word "Example".
In this particular RSS feed, the word example is in every feed. I would like to hide "example" and all text the follows that word. How can I accomplish this?
Though there is not enough jQuery, you even don't need it to remove everything after a certain word in the given string. The first approach is to use substring:
var new_str = str.substring(0, str.indexOf("Example"));
The second is a trick with split:
var new_str = str.split("Example")[0];
If you also want to keep "Example" and just remove everything after that particular word, you can do:
var str = "aaaa1111?bbb&222:Example=123456",
newStr = str.substring(0, str.indexOf('Example') + 'Example'.length);
// will output: aaaa1111?bbb&222:Example
jQuery isn't intended for string manipulation, you should use Vanilla JS for that:
newspan = newspan.replace(/example.*$/i, "");
The .replace() method accepts a regular expression, so in this case I've used /example.*$/i which does a case-insensitive match against the word "example" followed by zero or more of any other characters to the end of the string and replaces them with an empty string.
I would like to hide all text starting from the word "Example"
A solution that uses the simpler replace WITH backreferences so as to "hide" everything starting with the word Example but keeping the stuff before it.
var str = "my house example is bad"
str.replace(/(.*?) example.*/i, "$1") // returns "my house"
// case insensitive. also note the space before example because you
// probably want to throw that out.

Categories