How to remove + from string except at beginning using regex [duplicate] - javascript

This question already has answers here:
Replace all occurrences of character except in the beginning of string (Regex)
(3 answers)
Remove all occurrences of a character except the first one in string with javascript
(1 answer)
Closed 1 year ago.
I’m looking to remove + from a string except at the initial position using javascript replace and regex.
Input: +123+45+
Expected result: +12345
Please help

const string = '+123+45+'
console.log(string.replace(/([^^])\+/g, '$1'))
https://regexr.com/61g3c

You can try the below regex java script. Replace all plus sign except first occurrence.
const givenString = '+123+45+'
let index = 0
let result = givenString.replace(/\+/g, (item) => (!index++ ? item : ""));
console.log(result)

input = '+123+45+';
regex = new RegExp('(?!^)(\\+)', 'g');
output = input.replace(regex, '');
console.log(output);

Related

Spliting a string with multiple delimiters from an array [duplicate]

This question already has answers here:
Is there a RegExp.escape function in JavaScript?
(18 answers)
Closed 3 years ago.
I need to split a string by multiple delimiters.
My string is var str = "2$4#3*5"
My array of delimiters (separators) is var del = ["$","#", "*"]
I'm using a regular expression but it is not working.
str.split(new RegExp(del.join('|'), 'gi'));
The results should be ["2","4","3","5"]
However I'm getting an error SyntaxError: Invalid regular expression: /*/: Nothing to repeat
When I remove the * the resulting array is ["2$3',"3", "5"]
How can I split with multiple delimiters from an array of delimiters?
and why does this not work with $ and *?
You need to escape the special characters first - replace function from this answer:
var str = "2$4#3*5";    
var del = ["$", "#", "*"];    
const res = str.split(new RegExp(del.map(e => e.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join("|"), "gi"));
    
console.log(res);
Try like this.
I passed in the Regex expression in split.
var str = "2$4#3*5"
var res= str.split(/[$,#,*]+/)
console.log(res)

Get everything in string after a single comma [duplicate]

This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
How can I convert a comma-separated string to an array?
(19 answers)
Closed 4 years ago.
I have some problem with my string, the variable name is accountcode. I want only part of the string. I want everything in the string which is after the first ,, excluding any extra space after the comma. For example:
accountcode = "xxxx, tes";
accountcode = "xxxx, hello";
Then I want to output like tes and hello.
I tried:
var s = 'xxxx, hello';
s = s.substring(0, s.indexOf(','));
document.write(s);
Just use split with trim.
var accountcode = "xxxx, tes";
var result= accountcode.split(',')[1].trim();
console.log(result);
You can use String.prototype.split():
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
You can use length property of the generated array as the last index to access the string item. Finally trim() the string:
var s = 'xxxx, hello';
s = s.split(',');
s = s[s.length - 1].trim();
document.write(s);
You can use string.lastIndexOf() to pull the last word out without making a new array:
let accountcode = "xxxx, hello";
let lastCommaIndex = accountcode.lastIndexOf(',')
let word = accountcode.slice(lastCommaIndex+1).trim()
console.log(word)
You can split the String on the comma.
var s = 'xxxx, hello';
var parts = s.split(',');
console.log(parts[1]);
If you don't want any leading or trailing spaces, use trim.
var s = 'xxxx, hello';
var parts = s.split(',');
console.log(parts[1].trim());
accountcode = "xxxx, hello";
let macthed=accountcode.match(/\w+$/)
if(matched){
document.write(matched[0])
}
here \w+ means any one or more charecter
and $ meand end of string
so \w+$ means get all the character upto end of the sting
so here ' ' space is not a whole character so it started after space upto $
the if statement is required because if no match found than macthed will be null , and it found it will be an array and first element will be your match

Javascript get the string between two symbols [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 years ago.
I have the following string and I'm trying to retrieve the string between two symbols
http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_search&wpv-women-clothing[]=coats
I need to retrieve wpv-women-clothing[] or any other string between the last & and the last = in the URL
Should I use regex for this or is there a function in Javascript/jQuery already well suited for this?
Thanks
var str = "http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_search&wpv-women-clothing[]=coats";
var last =str.split('&').pop().split('=')
console.log(last[0]) // wpv-women-clothing[]
jsFiddle example
Split the string on the ampersands (.split('&')), take the last one (.pop()), then split again on the = (.split('=')) and use the first result last[0].
.*&(.*?)=.*
This should do it.
See demo.
http://regex101.com/r/lZ5bT3/1
Group index 1 contains your desired output,
\&([^=]*)(?==[^&=]*$)
DEMO
> var re = /\&([^=]*)(?==[^&=]*$)/g;
undefined
> while ((m = re.exec(str)) != null) {
... console.log(m[1]);
... }
wpv_post_search&wpv-women-clothing[]
Can you try:
var String = "some text";
String = $("<div />").html(String).text();
$("#TheDiv").append(String);

How to trim a string to its last four characters? [duplicate]

This question already has answers here:
How to get the last character of a string?
(15 answers)
Closed 8 years ago.
I know there are methods to remove characters from the beginning and from the end of a string in Javascript. What I need is trim a string in such a way that only the last 4 characters remain.
For eg:
ELEPHANT -> HANT
1234567 -> 4567
String.prototype.slice will work
var str = "ELEPHANT";
console.log(str.slice(-4));
//=> HANT
For, numbers, you will have to convert to strings first
var str = (1234567).toString();
console.log(str.slice(-4));
//=> 4567
FYI .slice returns a new string, so if you want to update the value of str, you would have to
str = str.slice(-4);
Use substr method of javascript:
var str="Elephant";
var n=str.substr(-4);
alert(n);
You can use slice to do this
string.slice(start,end)
lets assume you use jQuery + javascript as well.
Lets have a label in the HTML page with id="lblTest".
<script type="text/javascript">
function myFunc() {
val lblTest = $("[id*=lblTest]");
if (lblTest) {
var str = lblTest.text();
// this is your needed functionality
alert(str.substring(str.length-4, str.length));
} else {
alert('does not exist');
}
}
</script>
Edit: so the core part is -
var str = "myString";
var output = str.substring(str.length-4, str.length);

splitting a string based on delimiter [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I split a string, breaking at a particular character?
I have a string in following format
part1/part2
/ is the delimiter
now I want to get split the string and get part 1. How can I do it?
result = "part1/part2".split('/')
result[0] = "part1"
result[1] = "part2
split the string and get part 1
'part1/part2'.split('/')[0]
var tokens = 'part1/part2'.split('/');
var delimeter = '/';
var string = 'part1/part2';
var splitted = string.split(delimeter);
alert(splitted[0]); //alert the part1
var result = YourString.split('/');
For your example result will be an array with 2 entries: "part1" and "part2"

Categories