简体   繁体   中英

How to extract the string from certain character using javascript?

Hi i am new to programming. i want to extract string from particular character.

Consider the below string.

'<sometext id="2" name="username"/>hello'

I want to retrieve the "username" and text after /> which is "hello"

so basically i have this string as a value for an object property so something like

object  = {
              property_1: "<sometext id=\"2\" name=\"username\"/>hello",
          }

so i retrieve it using object.string_to_parse and store it in variable string_to_parse

let string_to_parse = object.property_1;

Now i want to get the string "username" from string_to_parse and store it in a separate variable and string "hello" from string_to_parse and store it in another variable.

How can i do it. could someone help me with this. thanks.

One potential solution to use here would be to split that string up and store the parts you need. Like such:

 let object = { property_1: "<sometext id='2' name='username'/>hello", }; let string_to_parse = object.property_1; let prop1; let prop2; prop1 = string_to_parse.split("name='")[1].split("'/")[0]; prop2 = string_to_parse.split('/>')[1]; console.log(prop1); console.log(prop2);

Regex should do the trick:

var str = '<sometext id="2" name="username"/>hello';

var re = /name="([^"]*)"/g
match = re.exec(str);
var uname = match[1];

var re = /\/>(.*)$/g
match = re.exec(str);
var msg = match[1];

The uname and msg variables have what you are trying to extract

Depends if you have only one or multiple ones of your separator "/>" . if we suppose we only have one you can get it with:

object.property_1.split("/>")[1] 

The split method helps you return 2 elements, one containing the string before the separator (here ">" ) and one containing the string after the separator.

Using this method you can easily get your username string, so I'll let you do this one yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM